A good[ish] website
Web development blog, loads of UI and JavaScript topics
Here I’m trying to figure out what forms the specificity in CSS? What is the good kind of specificity, and what is bad specificity. And how only to use only the good kind of specificity.
Specificity is the "weight" of the selector, upon the browser decides which style rule is the most relevant for the given element. In other words: which style rule has the most power.
It’s these 5 things:
!important
rule increases specificity.Let’s look at there one by one.
<style>
#my-button {
background-color: blue;
}
</style>
<button id="my-button" style="color: red;">Hello</button>
That button will be red.
Later on in the file defined rules have higher specificity:
.button {
background-color: blue;
}
.button {
background-color: red;
}
That button will be red.
The below button should be blue:
#button {
background-color: blue;
}
.button {
background-color: red;
}
That button will be blue:
body .button {
background-color: blue;
}
.button {
background-color: red;
}
The following button will also be blue:
button.button {
background-color: blue;
}
.button {
background-color: red;
}
.button {
background-color: blue !important;
}
.button {
background-color: red;
}
Results in blue button.
See this simple JSBin Demo.
1 Inline styles have higher specificity
This good, when adding a class to an element with JavaScript, it needs to override existing styles.
2 Selector order
We want the later rules in the file to have the power to override earlier rules.
I think, there is too many ways the element’s specificity can change, if we want to make our programming life simple, the selector order and inlining should be only two ways to affect selectors specificity.
Say you have a big website with +20 000 lines of CSS, and on a specific page you want to make element green on hover, rather than red, but you can’t, because somewhere in those +20 000 lines there is a rule with a higher specificity than your new rule, even if it comes last in the CSS. So now you have to use !important
to override the specificity and the vicious circle of specificity hell is set.
Here’s some quotes to set the mood of this section:
Only a madman would use the whole of C++
And one from the JavaScript Cthulhu, aka Crockford:
Most programming languages contain good parts and bad parts. I discovered that I could be better programmer by using only the good parts and avoiding the bad parts.
A pivotal moment in my working life was to to restrict my CSS to exclude the things that caused me pain:
!important
.Nothing is set in stone, there might be some cases where cascading is a great option. Not using IDs and discarding cascading doesn’t make you a good programmer, and using them will not make you a bad programmer.
Comments would go here, but the commenting system isn’t ready yet, sorry.