The Cascade of CSS
Specificity
1. ID selectors (most specific selector)
2. Class selectors
3. Type selectors
4. Universal selector (*) has no specificity value
- A CSS declaration that is more specific will take precedence over less specific ones.
- Specificity will only be taken into account when an element has multiple, conflicting declarations targeting it, sort of like a tie-breaker.
- When no declaration has a selector with a higher specificity, a larger amount of a single selector will beat a smaller amount of that same selector.
-
Examples:
<!-- index.html -->
<div class="main">
<div class="list subsection"></div>
</div>
/* styles.css */
/* rule 1 */
.subsection {
color: blue;
}
/* rule 2 */
.main .list {
color: red;
}
- In the example above, both rules are using only class selectors, but rule 2 is more specific because it is using more class selectors, so the
color: red;
declaration would take precedence.
<!-- index.html -->
<div class="main">
<div class="list" id="subsection"></div>
</div>
/* rule 1 */
#subsection {
color: blue;
}
/* rule 2 */
.main .list {
color: red;
}
- In the example above, despite rule 2 having more class selectors than ID selectors, rule 1 is more specific because ID beats class. In this case, the
color: blue;
declaration would take precedence.
Inheritance
- Typography based properties (
color
,font-size
,font-family
, etc.) are usually inherited, while most other properties aren’t.
<!-- index.html -->
<div id="parent">
<div class="child"></div>
</div>
/* styles.css */
#parent {
color: red;
}
.child {
color: blue;
}
- Despite the
parent
element having a higher specificity with an ID, thechild
element would have thecolor: blue
style applied since that declaration directly targets it, whilecolor: red
from the parent is only inherited.
Rule Order
- If no other factor (inheritance and specificity) is able to determine which rule to apply, the last one gets applied to the element.
/* styles.css */
.alert {
color: red;
}
.warning {
color: yellow;
}
.warning
rule gets applied.