• Understanding The Specificity in CSS

    Posted by Gaurav Arora | Last Updated: 29-Jun-18

    Hi Guys, In this blog, we will learn about Specificity in CSS

    Specificity is a means by which the browser decides which CSS attribute value is the most relevant to the element and will, therefore, be applied. The specificity is based on matching rules composed of different types of CSS selectors.

    Ids and class have more specificity on the other hand universal selector (*) has very low specificity.

    Sometimes you might have noticed that some CSS properties are not applied to some elements, even you have defined them properly in order but that still does not work and the reason for this is Specificity.


    Specificity Hierarchy

    Each selector has a place in a particular hierarchy. There are four different categories that define the specificity of a given selector:

    • Inline styles: Inline style is the style that we defined on HTML tags such as
    • IDs: An ID is a unique identifier on a single page and that should not be repeated.
    • Classes, attributes and pseudo-classes: Classes like .active, attributes like [active] and pseudo-classes like :active, :hover.
    • Elements and pseudo-elements: Elements such as div, span and pseudo-elements like: before: after.


    How to Calculate Specificity?

    We can easily understand the approach with the help of below snippet.

          color: green;
          color: blue;

    In the above example, I have taken three span tags one is normal, other with a class and the last one with an inline style that should be avoided, but I’m using it for the demo.

    As our span tag with an inline style defined on it, so that tag will have a higher level of specificity and the same would be apply to it. Inline style can be override only when if I mark !important to the span tag property in css that will be applied to it, because of the specificity of the CSS! An important decorator is more than the inline style and this is how specificity works.


    Avoid use of ! important

    When you use important rules in a style declaration, this statement overrides any other statement. Although technically what matters is that it does not relate to specificity and interacts directly with it. Use of ! important declaration is a very bad practice as breaks the natural cascade in the stylesheet, and it should be avoided. On the other hand, when two conflicting declarations with ! important rule defined on them, the declaration with the higher level of specify will applied to that element.

    Instead of using! important in the CSS one should find a way to use specificity in css, like to define ids and classes to the HTML elements so that we can can define specific styles according to that particular selector.

Tags: css