CSS specificity
Let's consider the following HTML:
<h1 class="my-class" id="my-id">What colour?</h1>
And the following CSS:
h1 {
color: red;
}
.my-class {
color: blue;
}
#my-id {
color: green;
}
Cascade
The C in CSS stands for cascading.
In this case, that means that these different CSS statements are fighting. They want the same text to be three different colours, so which one wins?
It's a matter of specificity.
CSS has some built-in rules for which selectors it considers more specific than others. The most specific selector wins.
In Codepen, you'll see that the text comes out as green. This is because the CSS statement using the ID is the most specific one.
If you remove it or comment it out, you'll see that the text turns blue. This is because the class selector is more specific than the tag selector.
Using specificity
We can use this behaviour to reduce the amount of CSS we need to write. Let's say that we want most of the headings on our website to be grey, with one or two exceptions, which should be blue.
We could write a CSS statement that turns all <h1>
elements grey, and use a class or ID to override the colour of the few exceptions.
The key to writing good CSS is writing statements that "fight" each other as little as possible. Write statements that are general enough to be useful, but not vague enough to be useless.
Bad CSS often ends up with increasingly specific statements trying to override each other in "specificity wars".
Part of Building webpages
- Your first webpage
- Introducing HTML
- HTML attributes
- Classes and IDs
- Introducing CSS
- CSS selectors
- CSS specificity
- Creating layouts
- Responsive design
- Get confident with HTML and CSS
- Turn your prototypes into webpagesP