CSS Selector

A CSS rule consists of two-part. The first part is called selector and the second part is called definition. CSS Selector is simply a pattern or multiple patterns which is helpful to select and style a particular element inside HTML. The definition specifies a set of key-value pairs to define the style of the element.

To select any HTML element, the most widely used techniques are using a tag, id, class, and attribute selectors. We can use any of the selectors, a combination of selectors, nesting of selectors to pick an element to style.

How to select any element in HTML:

Following is a syntax to define a selector in CSS:

Selector { key:value; }

A basic selector has a selector type and CSS style rules in between the curly brackets. There are different types of selectors in CSS with different presidential values. Let's look into the type of selectors and how to use them.

Selector Naming:

Valid selector names can start with A-Z, a-z, or with ( _ ) underscore or ( - ) hyphens. A selector can't start with a digit. Digits can be used followed by any valid prefix.

.validselector selector name

.VALIDSELECTOR selector name

(-) selector name

(_)selector name

10 selector name

--1 selector name

__1 selector name

CSS Tag Selectors:

Let’s start with the least priority selectors. They are tag selectors. You can select any valid HTML tags with tag names followed by the properties inside curly brackets for styling. This is the simple selector and the syntax looks like this.

p{ ... }

CSS Attribute Selectors:

Any tag containing attributes like title or any other attribute can be selected using attribute selector. Unlink tag selectors, attribute selector can select key and value. There are certain rules that can be applied to attribute selectors. You don't need to specify any tag with this selector. This will work on all elements with the specified attribute name and or value.

[attr] - Selects elements having an attribute or key specified in tag.

This is a div

This is a paragraph

[attr~=value] - Selects an element with an attribute matching exact value from multiple class lists specified as attribute values. This selector is used when we have an element with multiple classes.

This is a div with value = "yellow"
This is a div with value = blank space + yellow
This is a div value = yellow + blank space
This is a div with value Yellow [capital Y]
This is a div with value red + yellow
This is a div with value red + yellow-dark

[attr|=value] - Selects element with attribute matching exact value, value starting with subcode followed by - (hyphen). This selector can be used for tags with language values like en-US en-GB.

This is a div with value = "yellow"
This is a div with value = "yellow-dark"
This is a div with value = "yellow-light"
This is a div with value = blank space + yellow
This is a div value = yellow + blank space
This is a div with value Yellow [capital Y]
This is a div with value red + yellow
This is a div with value red + yellow-dark

[attr^=value] - Selects elements with prefixed value specified. This works only for the first matched value.

This is a div with value = "yellow"
This is a div with value = "yellow-dark"
This is a div with value = "yellow-light"
This is a div with value = blank space + yellow
This is a div value = yellow + blank space
This is a div with value Yellow [capital Y]
This is a div with value red + yellow
This is a div with value red + yellow-dark

[attr$=value] - Selects elements with suffixed value specified. This works only for the first matched value.

This is a div with value = "yellow"
This is a div with value = "yellow-dark"
This is a div with value = "dark-yellow"
This is a div with value = "yellow-light"
This is a div with value = blank space + yellow
This is a div value = yellow + blank space
This is a div with value Yellow [capital Y]
This is a div with value red + yellow
This is a div with value red + yellow-dark
This is a div with value dark-yellow + red

[attr*=value] - Selects elements containing at least one occurrence of value within the string. In CSS frameworks, columns can be initialised so all different selectors like .col-1 .col-2 .col-3 can have a common value just with one selector.

This is a div with value = "yellow"
This is a div with value = "yellow-dark"
This is a div with value = "dark-yellow"
This is a div with value = "yellow-light"
This is a div with value = blank space + yellow
This is a div value = yellow + blank space
This is a div with value Yellow [capital Y]
This is a div with value red + yellow
This is a div with value red + yellow-dark
This is a div with value dark-yellow + red

Attribute Comparision Flag:

[attr ... i]

using i or I before the closing bracket will make value comparison case insensitive.

This is a div with value = "yellow"
This is a div with value = blank space + yellow
This is a div value = yellow + blank space
This is a div with value Yellow [capital Y]
This is a div with value red + yellow

[attr ... s] 

Adding an s or S before the closing bracket will make value comparison case sensitive. There is no example because that's the default case with CSS selectors.

CSS Class Selectors:

Even classes can be selected with attribute selectors, but class selectors have more priority than attribute selectors. Class selectors specifically use class="value" attribute to select the element.

To select the element with a class (.) dot followed by value is used. For example

.red{...} selector will select  <div class="red" ></div> tag. But there is something more that can be done with classes.

Both the methods are the same for selection [class="pink"]  = .pink but the one that comes last in the code will get priority.

In the Below example, attribute takes the priority

This is a div with class = "pink"

If the class definition is below the attribute, it gets priority. So in case of conflict, the last rule takes priority.

This is a div with class = "pink"

But if still, we want to override our style, then we can add other selectors to the selectors, for example in our above example, the class selector can still win if it has higher specificity. By adding a tag like div.pink. See what happens.

This is a div with class = "pink"

Even the class selector is not at the bottom, but it has higher specificity because it has 2 selectors. Classes can be reused multiple times on the webpage.

CSS Pseudo Selectors:

These specify the particular state of the element and can be used to select elements in specific states like hover, active, etc.

Most useful pseudo classes are: 

  • :empty 
  • :first-child 
  • :last-child
  • :first-of-type 
  • :last-of-type
  • :hover 
  • :not(selector) 
  • :nth-child(n)
  • :only-child
  • :only-of-type

W3C has more details about all the pseudo classes and what they do.

These selectors are used for styling form elements and more interactive parts of the web page like Anchors, Buttons, Tables, etc. It's so much easy to select repeating patterns with selectors. For example:

This demo shows usage of :first-child, :last-child and :nth-child

This is a div

This is a paragraph

This is a paragraph

This is a paragraph

This is a div

This is a paragraph

This is a div

This is a paragraph

This is a div

This is a paragraph

This is a div

CSS ID Selectors:

ID has the highest specificity among all of the other selectors except inline CSS. Since inline CSS does not have any selectors, ID is considered the highest priority selector in CSS. IDs can be used only once on the page. But CSS will work for multiple ids even it's not correct. To select any element having id attribute, (#) hash is used followed by the attribute value. For example

#red{...} selector will select  <div id="red" ></div> tag. All rules and conflicts and priorities we discussed for class selectors are not applicable to ID selectors. ID will always take over tags, classes, and attributes.

In the below example, the ID takes over the other selectors because of its higher precedence over other selectors.

This is a div with id = "pink"

How to select Multiple elements:

To apply the same rule on multiple elements, a (,) is used as a separator.

.selector1, .selector2, .selector3{ … }

How to select element with multiple classes:

Just by using a combination of multiple class names without space.

.selector1.selector2

How to select an element of a parent:

Combine parent selector followed by child selector separated by space.

.parent .child

How to select the parent of a child:

Bummer! You can't. :P

How to Select Immidiat Child of a parent:

Use ( > ) greater than sigh as a separator between parent followed by a child.

.parent > .child

How to select the next Child of an element:

Use ( + ) plus as a separator between the first and second selector.

.element + .nextelement

How to select the previous Child of an element:

Not yet.

How to Select All Immediate Child of a parent:

Use ( ~ ) tilt as a separator between the first and second selector.

.parent ~ .children

How to select everything within the parent:

Use (*) as a selector to select everything inside relevant tags.

.parent *

Now you have an idea of how CSS selectors work, there is a way to override CSS even it's a high specificity rule.

Let's learn about specificity.

When we use selector combination, with multiple selectors, many times conflict can happen between the same precedence rules. Every selector has a Specificity value based on which it gets priority. Here are specificity values for each type of selector.

Type of selectors and their Specificity Value:

1,0,0,0 - Inline Style: This style applies directly to the HTML tag itself. So there are no rules. Just key-value pairs of properties can be used to style the element directly. Its value is considered as a number in thousand.

0,1,0,0 - ID Selector: any element having id attribute assigned to the tag will have the heist specificity value. Its value is considered as a number in hundreds. Id is used exactly once on the entire page, so it can’t be used twice in the same selector, however, it can be combined with other id selectors.

0,0,1,0 - Class Selector: any tag having a class attribute will get precedence in tens. Multiple elements of the same type will increase the count of tens. This type includes class, pseudo-classes, pseudo-elements, attribute selectors.

0,0,0,1 - Tag Selector: Any tag without any attribute adds up a value in the last digit.

Note: Don't get confused with these numbers,  These values are not in thousands but infact they all have their separate column, A selector with 10 classes will have a specificity of 0,0,10,0 and not 0,1,0,0. The selectors' type count adds up in its own column and not the next digit as you expect in math.

So, now you know about CSS selectors, combinators and about their specificity,

Let's look at some complex selectors and evaluate their specificity.

id class element selector
0 0 1 div
0 0 2 div + div
0 0 2 div > div
0 0 2 div ~ div
0 1 0 .class
0 1 1 div.class
0 2 1 div.class1.class2
0 1 2 div.class1 div
0 1 2 div div.class1
0 2 2 div:first-child div.class1
1 0 0 #id
1 0 1 div#id1
1 1 2 div#id1 div
1 1 2 div#id1 div.class1
2 0 2 div#id1 div#id2
2 1 2 div#id1 div#id2.class1
2 2 2 div#id1 div#id2.class1.class2

How to use CSS selectors efficiently?

When creating a webpage, Before thinking of web site as a whole, Thinks of smaller components that the page might have. The best approach is to create your selectors as follows:

  • Create global selectors for sitewide elements like grid and content elements. Selectors for most commonly used objects with low specificity, in general, can be easily overridden.
  • Create component-based selectors for specific parts of the website like header, breadcrumb, hero image, content, sidebar, footer, etc.
  • Go down more step in each of the above components, and create child selectors like navigation, logo, widgets, etc
  • Keep selectors organized in different CSS files or with comments blocks for each rule block if not in separate files.

Final Words:

There is more than one way to select an HTML element. One should use the CSS selectors efficiently to make code organized and more usable, With a proper selector, you can reduce the line of code and increase its global re-usability. Now you know everything about CSS Selectors, You can check about the cascading behavior of CSS by checking how CSS inheritance works and how to override CSS properties.

Leave a Reply

Your email address will not be published. Required fields are marked *