Selector

10 Aug 2023 . css .

Specificity

If there are two or more declarations providing different property values for the same element, the declaration value in the style block having the matching selector with the greatest algorithmic weight gets applied.

Selector weight categories

ID column

ID selectors, such as #example. Add 1-0-0 to the weight value.

CLASS column

class selectors, such as .myClass, attribute selectors like [type=“radio”] and pseudo-classes, such as :hover. Add 0-1-0 to the weight value.

TYPE column

type selectors, such as p and pseudo-elements like ::before. Add 0-0-1 to the weight value.

Three-column comparison

The number of selector components in each column are compared, from left to right. If the competing selectors have the same values in all the three columns, the last declared style gets precedence.

What elements match a selector

Browsers match selectors from rightmost to left. For example with this selector p span, browsers firstly find all the <span> elements and traverse up its parent all the way up to the root to find the <p> element.

Pseudo-elements

A keyword added to a selector that lets you style a specific part of the selected elements. For example, :first-line and :first-letter can be used to decorate text.