CSS Specificity

CSS Specificity is a crucial concept that dictates which styles are applied to elements. It is a set of rules used by browsers to decide which CSS property values will be applied to an element when there are conflicts.

In this lesson, you will learn how to navigate through the intricacies of CSS Specificity. Learn how browsers decide which CSS rules to apply when conflicts arise, and master the art of crafting CSS that behaves as expected.

Desired Outcomes

  • Understand the principles of CSS Specificity
  • Solve conflicts between CSS rules effectively
  • Write more predictable and maintainable CSS

How to calculate specificity

  1. Inline styles: An inline style attribute present on an element will override any styles in external stylesheets and will have the highest level of specificity.
  2. IDs: Each unique ID will add to the specificity.
  3. Classes, pseudo-classes, and attributes: Each unique class, pseudo-class, or attribute will add to the specificity.
  4. Elements and pseudo-elements: Each unique element or pseudo-element will add to the specificity.

The specificity is calculated as follows:

Start at 0, add 100 for each ID value, add 10 for each class value (or pseudo-class or attribute selector), add 1 for each element selector or pseudo-element.

Let's see an example:

body #content .data {  
  background-color: blue;  
}  

This selector contains 1 element, 1 ID and 1 class selector, so it would have a specificity of 1,100, 10. Which means that the overall specificity of this selector is 111. So to override it, you would need to write a selector which has the specificity level larger than 111.

Equal specificity: the latest rule wins - If the same rule is written twice into the external style sheet, then the latest rule wins:

h1 {color: blue;}
h1 {color: red;}

Example of Specificity in Action

Let's see a real-world example:

HTML

<div id="content" class="main">
  <p class="highlight">Hello, world!</p>
</div>

CSS

p {
  color: blue;
}

.main .highlight {
  color: red;
}

#content p {
  color: green;
}

p.highlight {
  color: yellow;
}
CSS Specificity
CSS Specificity

The color of the text will be green because the #content p selector has the highest specificity. It contains 1 ID and 1 element, so it has a specificity of 1,0,1. All the other selectors have lower specificity.

The specificity can lead to confusing results if not managed properly, so it's good to keep your CSS selectors as simple as possible and avoid unnecessary complexity.

-75%

Time remaining:
days 00: 00: 00

Learn to code HTML & CSS

From Zero to Hero

Check out this course on Udemy, now at 75% off! Inside this interactive course, I will teach you how to develop websites from scratch moving from beginner to advanced concepts. I take time to explain every detail and finish off by building some real-world websites.

HTML & CSS: From Zero to Hero
Learn to code HTML & CSS