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.
ID selectors, such as #example
. Add 1-0-0 to the weight value.
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 selectors, such as p
and pseudo-elements like ::before
. Add 0-0-1 to the weight value.
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.
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.
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.