BETAThis is a new service – your feedback will help us to improve it.

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;
}
Copy this HTML and CSS over into Codepen and see what colour the text ends up.

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".

Making good use of the CSS cascade lets us avoid...

Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Building webpages
  1. Your first webpage
  2. Introducing HTML
  3. HTML attributes
  4. Classes and IDs
  5. Introducing CSS
  6. CSS selectors
  7. CSS specificity
  8. Creating layouts
  9. Responsive design
  10. Get confident with HTML and CSS
  11. Turn your prototypes into webpagesP