Specificity in CSS

Jul 18, 2024

Specificity in CSS

Introduction

  • Specificity in CSS determines which style rules apply in cases of conflicting styles.
  • Example: Two conflicting styles on an element for background color (red vs yellow).
  • Cascade algorithm helps determine which style to apply.

Cascade Algorithm

  • CSS: Cascading Style Sheets.
  • Resolves conflict using 4 rules.
  • Determines which property will be applied.

Four Rules of the Cascade Algorithm

  1. **Position and Order of Appearance:

    • Later positioned properties overwrite earlier ones if selectors are of the same type.
    • Example: .c-purple and .c-red, the latter one applies if both selectors are equal.
  2. **Specificity Calculation:

    • Inline styles are most specific, then ID selectors, class/attribute selectors, element selectors, and the universal selector.
    • Use the least specific selector for easier overwriting.
  3. **Origin of CSS:

    • Importance of user-agent stylesheets (default browser styles).
    • Styles written by the user will overwrite user-agent styles.
  4. **Importance (using !important):

    • Overrides all other specificity including inline styles.
    • Last resort since it makes further overwriting difficult.

Specificity Calculation

  • Universal Selector (*): 0 points.
  • Element Selector or Pseudo Elements: 1 point.
  • Class Selector, Attribute Selector, or Pseudo Classes: 10 points.
  • ID Selector: 100 points.
  • Inline Styles: 1000 points.
  • Example: Three classes are .yellow, .c-purple, and .c-red each having specificity 10. The one appearing last will apply.

Calculation Example

  • h1.yellow -> h1: 1 point, .yellow: 10 points → Total: 11 points.
  • Combined selectors (e.g., a.red) add up their values.

Practical Examples

  1. Inline Style Priority:
    • Example: style="color: blue;" applied directly to the tag will override other CSS rules.
  2. ID Selector Priority:
    • Example: #example {color: red;} will have higher precedence over class selectors .example {color: red;}.
  3. Attribute Selector:
    • Example: [data-example="true"] {color: green;} can target elements with specific attributes.
  4. Using !important:
    • Example: .example {color: red !important;} will override inline styles as well.

Summary

  • Use CSS selectors wisely based on their specificity levels.
  • Aim for less specific selectors for easier maintenance and overwriting.
  • Inline styles and !important should be used sparingly as they are hard to override.