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

爱⌒轻易说出口 提交于 2019-11-29 16:56:47

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

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>

As commented/answered above, ID will always win but here is a trick to make your classes win.

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

.one.two.three.four.five.six.seven.eight.nine.ten.eleven:not(#random_id) {
  background-color: red; 
}
<div id="box" class="one two three four five six seven eight nine ten eleven"></div>

Why this works when we know that pseudo-classes are less specific than ID?

Simply because The :not() itself doesn't add anything to the specificity number as other pseudo-classes do. However, the selectors within the :not() do.ref

So it's like i added an ID to my class selectors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!