CSS: Specificity

Specificity in CSS is a crucial concept that determines which style rules apply to an element when multiple rules could apply. It’s like a scoring system that decides which rule “wins” in a conflict. Here’s how it works:

  • Inline styles, added directly to an element’s style attribute, have the highest specificity. If you set a style in this way, it generally overrides any style set in <style> tags or external style sheets.
  • IDs are the next most specific; a single ID is more specific than any number of other attributes.
  • Classes, attributes, and pseudo-classes come next in the specificity hierarchy.
  • Elements and pseudo-elements are the least specific.

The specificity score can be thought of as a series of numbers: inline styles (1,0,0,0), IDs (0,1,0,0), classes/attributes/pseudo-classes (0,0,1,0), and elements/pseudo-elements (0,0,0,1). When comparing specificity, the highest number on the left “wins”. If there’s a tie, the rule that comes last in the code will prevail.

Here’s an example to illustrate:

CSS

/* Specificity (0,0,0,1) */
body {
  color: blue;
}

/* Specificity (0,0,1,0) */
.myclass {
  color: green;
}

/* Specificity (0,1,0,0) */
#myid {
  color: red;
}

/* Inline style has a specificity of (1,0,0,0) */
<p id="myid" class="myclass" style="color: pink;">Hello World!</p>

Remember, the universal selector (*), combinators (+, >, ~,  , ||), and negation pseudo-class (:not()) have no effect on specificity. The :not() pseudo-class adds to the specificity of the selector inside its parentheses.