I'd like to understand how CSS selectors work with property collisions. How is one property selected over another one?
div { background-color: red; } div.my_class { background-color: black; } div#my_id { background-color: blue; } body div { background-color: green; } body>div { background-color: orange; } body>div#my_id { background-color: pink; }
<div id="my_id" class="my_class">hello</div>
How does selector priority work?
Memorize how to calculate specificity! Start at 0, add 100 for each ID value, add 10 for each class value (or pseudo-class or attribute selector), add 1 for each element selector or pseudo-element. Note: Inline style gets a specificity value of 1000, and is always given the highest priority!
Rule 3: Inline CSS has the highest specificity. Inline CSS is the closest to the HTML element, so it is more specific and is therefore applied.
The priority level of the selector is decided in Point of combination of selectors. "article p span" are "a=0, b=0, c=0, d=3 (0003)". "#red" is "a=0, b=1, c=0, d=0 (0100)".
I'll just toss in a link to the CSS 2.1 spec itself, and how browsers are supposed to calculate specificity:
CSS 2.1 Section 6.4.3:
A selector's specificity is calculated as follows:
- count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
- count the number of ID attributes in the selector (= b)
- count the number of other attributes and pseudo-classes in the selector (= c)
- count the number of element names and pseudo-elements in the selector (= d)
- The specificity is based only on the form of the selector. In particular, a selector of the form "[id=p33]" is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source document's DTD.
Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.
If the specificities are equal, then CSS 2.1 Section 6.4.1 comes into play:
- Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.
Note that this is talking about when the style is defined, not when it is used. If classes .a
and .b
have equal specificity, whichever is defined last in the stylesheet(s) wins. <p class="a b">...</p>
and <p class="b a">...</p>
will be styled identically, based on the definition order of .a
and .b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With