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

蓝咒 提交于 2019-12-18 09:27:16

问题


#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


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/49741961/why-is-this-11-class-selector-less-specific-than-the-id

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