Search code examples
csscss-selectorscss-specificity

Why is this 11 class selector less specific than the ID?


#box {
  width: 100px;
  height: 100px;
  background-color: #ff0;
}

.one.two.three.four.five.six.seven.eight.nine.ten.eleven {
  background-color: #f00;
}


<div id="box" class="one two three four five six seven eight nine ten eleven"></div>

If the following points are given to each type of selector, then how come the above class selector does not override the ID selector?

Style attribute: 1,0,0,0 ID: 0,1,0,0 Class, pseudo-class, attribute selector: 0,0,1,0 Element: 0,0,0,1


Solution

  • Because the CSS specificity point system is exactly as you have specified:

    • Style attribute: 1,0,0,0
    • ID: 0,1,0,0
    • Class, pseudo-class, attribute selector: 0,0,1,0
    • Element: 0,0,0,1

    Specificity

    The commas are there to remind us that this isn't really a "base 10" system, in that you could technically have a specificity value of like 0,1,13,4 - and that "13" doesn't spill over like a base 10 system would.

    Your ID selector is 0,1,0,0, and your combined class selector is 0,0,11,0.

    At no point will any combination of class selectors ever override a single ID selectors, as is seen in the following:

    #box {
      width: 100px;
      height: 100px;
      background-color: #ff0; /* yellow */
    }
    
    .one.two.three.four.five.six.seven.eight.nine.ten.eleven {
      background-color: #f00; /* red */
    }
    <div id="box" class="one two three four five six seven eight nine ten eleven"></div>