Continuing from Day 004.
Selector specificity is another criterion the cascade uses to resolve conflicts.
In all my learning of CSS, this has always been the biggest stumbling block. I just couldn't make sense of it, and that's partly why I wasn't interested in front-end for a long time, until now.
Selector specificity is about how specific a selector is inside an external CSS stylesheet. This is separate from stylesheet origin. If the cascade cannot resolve declaration conflicts using stylesheet origin (including the important flag and inline styles), it turns to selector specificity within the author stylesheet.
To understand this better, there's a notation system that uses numbers to measure specificity. It's based on the following selectors: IDs, Classes, and Tags. Some systems also include inline styles in the notation.
For example:
- Without inline styles: IDs have the highest specificity, followed by Classes, then Tags.
- With inline styles: Inline styles take the highest specificity.
Given the following CSS rules:
h1 {
color: #2f4f4f;
margin-bottom: 10px;
}
#main-nav {
margin-top: 10px;
list-style: none;
padding-left: 0;
}
#main-nav li {
display: inline-block;
}
.nav {
color: red;
}
The specificity breakdown looks like this:
- h1 : 0,0,1 (no ID, no Class, one Tag)
- #main-nav : 1,0,0 (one ID, no Class, no Tag)
- #main-nav li : 1,0,1 (one ID, no Class, one Tag)
- .nav : 0,1,0 (no ID, one Class, no Tag)
According to Keith, the exact rules of specificity are:
- If a selector has more IDs, it wins.
- If that results in a tie, the selector with more Classes wins.
- If that still ties, the selector with more Tags wins.
I also learned that when inline styles are present, the notation includes an extra placeholder: Inline, ID, Class, Tag (x,x,x,x). Inline styles carry a weight of 1,0,0,0
.
This cleared up a lot for me because I used to wonder why some of my styles didn't apply. Now I can quickly tell the specificity of selectors just by using this notation.
A helpful note from Keith:
- Pseudo-class selectors (like
:hover
) and attribute selectors (like[type="input"]
) have the same specificity as a Class. - The universal selector (
*
) and combinators (>
,+
,~
) do not affect specificity.
Tip: It's best to keep specificity low so that overriding rules later is easier.
I believe anyone can become a CSS Pro, and therefore I am.
Top comments (0)