DEV Community

Cover image for CSS Specificity
Joel Lau
Joel Lau

Posted on

CSS Specificity

This articles assumes a basic understanding of HTML and CSS

Most beginners quickly come to understand that elements on a page inherit every rule that applies to it, accumulating styles. However, few understand what happens when multiple rules apply to the same element - the selector which is more specific takes priority. Conversely, rules that are less specific are overridden.

Calculating Specificity

In order to determine how specific a selector is, we must first determine the number of items that are present in each of the 4 categories.

  1. html style attributes
  2. ids (id attribute)
  3. other attributes (including class), pseudo-classes (e.g. :link, :hover)
  4. elements, pseudo-elements(e.g. :before, :after)

When we have the number of items in each category, concatenate them back-to-back to form a final value. Like number systems with a large base, a number in a larger category always beats the number in a smaller category.

<style type="text/css">
    /* priority: 0,0,0,1 */
    p {
        color: black;
        font-weight: bold;
    }

    /* priority: 0,0,1,1 */
    p.para {
        color: blue;
        margin-left: 1rem;
    }

    /* (smaller priority that p.para)
        priority: 0,0,1,0 */
    .para {
        color: green;
    }


</style>
<!-- (style attribute) priority: 1,0,0,0 -->
<p class="para" style="color: purple">
    Hello World
</p>
Enter fullscreen mode Exit fullscreen mode

In this example, the text will appear purple because the style attribute has the highest priority and inherit other rules (font-weight, margin-left) that were applied.

!important

The final consideration when trying to determine which CSS rules are applied is the !important keyword. By appending this to any CSS value, it increases its priority by another degree. !important rules are sorted and applied in order of specificity with other !important rules before normal rules are considered.

However, using !important often breaks the design of carefully crafted style sheets and should be avoided!

Conclusion

By developing a thorough understanding of how specificity works, we can easily control which styles are applied by increasing or decreasing a selector's specificity. This allows us to elegantly design succinct style sheets that follow DRY principles.

If you liked this article, give me a shoutout on Twitter at @JoelLau93 or let me know how I can do better!

Further Reading:
https://www.w3.org/TR/CSS2/cascade.html

Top comments (0)