Order & Specificity
When writing CSS, if there are two declarations that are trying to do the same thing, the browser needs to decide which of those to use.
To make that decision, it will first look at the specificity of the selectors. If one has higher specificity, it will win. However, if they both have the same specificity, then order comes into play.
We’ll start with order because it’s the easiest to understand.
Let’s say you had this declaration:
p { color: black; color: white;}In this situation, our paragraphs would be white, because with two equivalent declarations, the last one will always win. They don’t need to be in the same rule, either.
p { color: black;}
p { color: white;}Once again, our paragraphs are white.
Which would win?
Section titled “Which would win?”If we have the following CSS:
.red { color: red;}
.blue { color: blue;}And then this HTML:
<p class="blue red">What color am I?</p>What color would the text inside the paragraph be?
Specificity
Section titled “Specificity”However, if we use a different type of selector, it’s possible that things change.
<p class="black-text">Hello world</p>.black-text { color: black;}
p { color: white;}This time around, our text will be black!
That’s because classes have higher specificity than element selectors, which makes sense. A p selects all of my
paragraph elements, so it’s very generic, while .black-text only selects elements that I’ve specifically added that
class to.
IDs are higher than both element and class selectors.
<article> <h2 id="article-title" class="black-text">Specificity & The Cascade</h2></article>#article-title { color: deeppink;}
.black-text { color: black;}
h2 { color: white;}In this case, our <h2> will be pink. The same logic applies, as we can only use a given ID one time per page, so it’s
very specific, and so selectors using it will always win.
Combining selectors
Section titled “Combining selectors”You can combine different types of selectors together, and when we do that, we add the specificity of them together.
/* equivalent to 1 element + 1 ID selector */h2#article-title { color: orangered;}
/* equivalent to 1 element + 1 class selector */h2.black-text { color: black;}Many people treat it as a points system, where an ID is worth 100 points, a class is worth 10 points, and an element one point. This is a little misleading though, as a single ID will still win over a selector that uses 10+ classes (please never have a selector that has 10+ classes).
There are a few specificity calcualtors out there that you can use, and you can also see the specificity of a selector in your DevTools by hovering over it.
What would happen here?
Section titled “What would happen here?”If we had the following HTML and CSS, what would the <h2> element looks like?
<main id="main"> <h2 class="title">What do I look like?</h2></main>h2,.title,#main { color: red;}
#main > .title { color: blue;}
h2.title { color: green; text-transform: uppercase;}