CSS Selectors

A CSS selector selects the HTML element(s) you want to style.

Simple Selector

Simple selector form is a single or specific element to which the property and value is applied.

We can also apply property and value to group of elements.

Example

See the Pen simple selector by Arpit (@soniarpit) on CodePen.

Class Selector

Using class selector we can apply different styles to the same element.

These different styles appear on different occurrences of the elements.

To select elements with a specific class, write a period (.) character, followed by the class name.

See the Pen class selector by Arpit (@soniarpit) on CodePen.

 A class name cannot start with a number!

Id selector

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

See the Pen id selector by Arpit (@soniarpit) on CodePen.

An id name cannot start with a number!

Universal Selector

This selector is denoted by asterisk (*) sign. This selector can be applied to all the elements in the HTML file.

See the Pen universal selector by Arpit (@soniarpit) on CodePen.

Attribute Selector

CSS allows us to specify rules that match elements which have certain attributes defined in the source element.

syntax

[att] - Match when the element sets the “att” attribute, whatever the value of the attribute

[att=val] - Match when the element’s “att” attribute value is exactly “val”

In following example all the <a> elements get selected with a target attribute. And also target="_self"

See the Pen attribute selector by Arpit (@soniarpit) on CodePen.

Contextual Selector

Contextual selector in CSS allow you to specify different styles for different parts of your document

You can assign styles directly to specific HTML tags or you can create independent classes and assign them to tags in the HTML

See the Pen contextual selector by Arpit (@soniarpit) on CodePen.

Previous: CSS Comments

Next: CSS Backgrounds