[class$=" "] 和 [id*=" "] 有什么特殊性?

What specificity does [class$=" "] and [id*=" "] hold?

[class$=" "]
[class*=" "]
[class^=" "]

以上所有内容(以及 ID 等效项)似乎都不遵循标准 CSS 特异性权重规则。

我做了一个 Codepen 来展示它们是多么的古怪和矛盾。 http://codepen.io/mildrenben/pen/myYLmG

标记

<div id="wrap">
  <div class="container">
    <p> #idName is more specific than [id*="idName"]. But .className and [class*="className"] seem to be the same specificty.</p>
  </div>
</div>

CSS

#wrap {
  border: solid 5px green;
}

[id*="wrap"] {
  border: solid 5px red;
}

.container {
  background: red;
}

[class*="container"] {
  background: yellow;
}

p {
  font-family: sans-serif;
  padding: 6px;
}

谁能澄清一下这些选择器的特异性权重?

谢谢

#idName is more specific than [id*="idName"]. But .className and [class*="className"] seem to be the same specificty.

是的。那就是the spec says they should be.

count the number of ID selectors in the selector (= a)

count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)

您有一个 ID 选择器、两个属性选择器、一个 class 选择器和一个类型选择器。

CSS特异性权重有四个部分,for example:0,0,0,0

  • 编号:0,1,0,0
  • class,属性,伪classes: 0,0,1,0
  • 元素、伪元素:0,0,0,1
  • “+”或“*”或“>”:0,0,0,0

例如

example1:  #header .container[name="1"] div {  } 
example2:  #header div div div div div div div p p p h2::before {  }

example1_specificity = id + class + attribute + element = 0,1,2,1
example2_specificity = id + pseudo-class + element*11  = 0,1,1,11

特异性会从左到右比较四个部分,直到一个比另一个大,所以example1_specificity更大

  • 当特异性相等时,一个接一个获胜
  • !important 将赢得任何特异性
  • 0,0,0,0特异性将胜出继承

希望对你有所帮助