Specificity is one of the most difficult topics to grasp in CSS but it doesn’t have to be. It requires two things:
- Basic math. (How to add, really.)
- How to tell the difference between an HTML element (a tag), a class, an id, and a pseudo-element
That’s it. Let’s look at an example:
Say you’ve got this in your styles:
ul li { color: black; }
li { color: red; }
What will the color of list items (li) be? Is it red, because it comes last? Is it black because we’ve got two tags in the style? The correct answer is black, but not just because we have two tags in the style. It’s because that style declaration’s specificity is greater.
Here’s the specificity math:
element selectors (HTML tags) = 1
pseudo-element selectors = 1
class selectors = 10 (also psuedo-classes and attributes)
id selectors = 100
inline style = 1000
Looking back at the list items, the style with both the ul tag and the li tag has a specifity value of 2 (1 + 1) while the li by itself has a value of 1.
Let’s look at some of the styles on slash25.com.
p {
line-height: 1.5em;
margin-bottom: 1.5em;
}
Specificity = 1
div.entry div p {
font-family: "gill sans",helvetica, sans-serif;
font-weight: 100;
font-size: 90%;
letter-spacing: 1px;
}
Specificity = 13
10 for .entry, 1 for div, 1 for div, 1 for p
What about the link styles?
a {
color: #00a0ea;
text-decoration: none;
border-bottom: 1px dotted #00a0ea;
}
Specificity = 1
a:hover, a:focus {
color: #000;
border-bottom: 1px solid #000;
}
Specificity = 11 (there are two styles, each with a specificity value of 11)
10 for :hover (or :focus), 1 for a
#subNav li li a:hover,#subNav li li a:focus {
color: #000;
border-bottom: none;
}
Specificity = 113 for each.
100 for #subNav, 10 for :hover (or :focus), 1 for li, 1 for li, 1 for a
Remember these basics and you’ll be able to calculate specificity like a pro. Then, the order in which a style appears in the CSS won’t matter as much because you’ll be able to increase the specificity of a style and have your desired effect come to life.
Are there caveats? Like all things in life, yes. The linked URL in this goes to a wonderful Smashing Magazine article in which they go into great depth. I would recommend if you’re stuck and everything seems to not work, drop us a comment or visit that article and see if you can’t figure it out.
Tags: css, specificity

