Skip to main content

Selector Specificity in CSS (Live Playground)

Selector specificity in CSS determines the priority of styles applied to elements based on the complexity of the selectors used. In this tutorial, you will learn about selector specificity, how it affects the application of styles, and how to calculate specificity values, along with sample code and simple explanations.

Understanding specificity

Specificity determines which styles are applied to an element when multiple rules target it. The rule with the highest specificity value takes precedence. Specificity is calculated using the following hierarchy:

  • Inline styles (highest specificity)
  • ID selectors
  • Class, attribute, and pseudo-class selectors
  • Element and pseudo-element selectors (lowest specificity)

Calculating specificity

To calculate specificity, count the number of selectors of each type in a rule, and represent them as a series of numbers. The rule with the highest specificity value will be applied.

Example:

CSS
/* Specificity: 0,0,1,0 */
p.special {
color: red;
}

/* Specificity: 0,1,0,0 */
#unique {
color: green;
}

/* Specificity: 0,0,0,1 */
p {
color: blue;
}
HTML
<p class="special" id="unique">This paragraph will be green.</p>

In this example, the paragraph has three styles competing for the color property. The #unique rule has the highest specificity (0,1,0,0) and takes precedence, making the paragraph green.

Live Playground, Try it Yourself

Importance of the !important rule

The !important rule can be added to a style declaration to give it higher priority over other rules. This should be used sparingly, as it can make your CSS harder to maintain and override.

Example:

CSS
p {
color: red !important;
}

p.special {
color: blue;
}
HTML
<p class="special">This paragraph will be red.</p>

In this example, the color: red !important; declaration takes precedence over the color: blue; declaration due to the !important rule, making the paragraph red.

Live Playground, Try it Yourself

Conclusion

In this tutorial, you learned about selector specificity in CSS and how it affects the application of styles to elements. Understanding specificity is essential for maintaining clean, organized CSS and ensuring that your styles are applied correctly. By carefully considering specificity when writing your CSS, you can create more predictable and manageable styles for your web pages.