CSS Specificity

CSS specificity determines which rules apply to an element when multiple rules could apply. It is a measure of the importance of a selector in the cascade process.

Specificity Rules

Specificity is calculated based on the types of selectors used in the rule. It is typically expressed as a four-part value, like (a, b, c, d):

  • a: Inline styles (e.g., style="color: red;") get a value of 1 in this column.
  • b: Counts the number of ID selectors in the selector.
  • c: Counts the number of class selectors, attributes selectors, and pseudo-classes.
  • d: Counts the number of element selectors and pseudo-elements.

Specificity Calculation

Here’s how specificity is calculated:

  1. Inline styles: Always have the highest specificity, represented by (1, 0, 0, 0).
  2. ID selectors: Each ID selector increases the b component by 1.
  3. Class selectors, attributes, and pseudo-classes: Each increases the c component by 1.
  4. Element selectors and pseudo-elements: Each increases the d component by 1.

Examples

  1. Inline Styles
    <div style="color: red;"></div>
    

    Try It Now

    Specificity: (1, 0, 0, 0)

  2. ID Selector
    #main {
        color: blue;
    }
    

    Try It Now

    Specificity: (0, 1, 0, 0)

  3. Class Selector
    .highlight {
        color: green;
    }
    

    Try It Now

    Specificity: (0, 0, 1, 0)

  4. Element Selector
    p {
        color: black;
    }
    

    Try It Now

    specificity: (0, 0, 0, 1)

  5. Combination
    #main .highlight p {
        color: orange;
    }
    

    Try It Now

    Specificity: (0, 1, 1, 1)

Overriding Specificity

  1. More Specific Rule: A more specific rule will override a less specific rule.
    p {
        color: black;
    }
    .highlight p {
        color: green;
    }
    

    Try It Now

    The color of p inside .highlight will be green because .highlight p is more specific.

  2. Order of Appearance: If two selectors have the same specificity, the one that appears last in the CSS will take precedence.
    p {
        color: black;
    }
    p {
        color: red;
    }
    

    Try It Now

    The color of p will be red because the second rule overrides the first one.

!important Rule: Adding !important to a declaration will override any other declarations, regardless of specificity.

p {
    color: black !important;
}
.highlight p {
    color: green;
}

Try It Now

  1. The color of p will be black because !important takes precedence over normal specificity rules.

Practical Tips

  • Use ID selectors sparingly to avoid overly specific rules that are hard to override.
  • Use class selectors for reusable styles.
  • Avoid using inline styles unless necessary as they have high specificity and can be difficult to override.
  • Use !important sparingly as it makes debugging more challenging.

 

Understanding CSS specificity helps in writing efficient and manageable stylesheets, ensuring the right styles are applied to elements as intended.