属性选择器的特殊性是什么?

Roh*_*zad 19 html css css-selectors css-specificity

我想知道属性选择器的特殊性是什么.例如:

  • Id = 100分
  • 等级= 10分
  • Html Tag = 1分

例:

/* this specificity value is 100 + 10 + 1 = 111 */
#hello .class h2 { }
Run Code Online (Sandbox Code Playgroud)

使用此HTML:

<div class="selectform">
<input type="text" value="inter text">
<input type="text" value="inter text" class="inputag">
</div>
Run Code Online (Sandbox Code Playgroud)

这两个选择器中哪一个更具体?

.selectform input[type="text"] { }
.selectform .inputbg { }
Run Code Online (Sandbox Code Playgroud)

查看演示 http://tinkerbin.com/IaZW8jbI

Bol*_*ock 22

属性选择器同样特定于类选择器.

在您的示例中,第一个选择器更具体,因为有一个额外的类型选择器input使其击败第二个选择器.

每个选择器的特异性计算如下:

/* 1 class, 1 attribute, 1 type -> specificity = 0-2-1 */
.selectform input[type="text"] { }

/* 2 classes                    -> specificity = 0-2-0 */
.selectform .inputbg { }
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,因为`#foo {}`具有1-0-0的特异性,而`[id ="foo"] {}`选择相同的元素但具有*0*低1-0的特异性. (5认同)