二维码

CSS 特异性

CSS 特异性

什么是特异性?

如果有两个或多个指向相同的 CSS 规则 元素,则具有最高特异性值的选择器将“获胜”,其样式声明将应用于该 HTML 元素。

将特异性视为确定哪种样式声明的分数/排名 最终应用于元素。

请看以下示例:

示例 1
1
2
3
4
5
6
7
8
9
10
11
12
在此示例中,我们使用 “p” 元素作为选择器,并指定了红色 对于此元素。文本将为红色:

<html>
<head>
  <style>    p {color: red;}  </style>
</head>
<body>

<p>Hello World!</p>

</body>
</html>

现在,请看示例 2:

示例 2
1
2
3
4
5
6
7
8
9
10
11
12
13
在此示例中,我们添加了一个类选择器(名为“test”),并且 指定为绿色 此类的颜色。文本现在将是绿色的(即使我们指定了 一个红色的 元素选择器的颜色 “P”)。这是因为给出了类选择器 更高的优先级:

<html>
<head>
  <style>    .test {color: green;}
    p {color: red;}  </style>
</head>
<body>

<p class="test">Hello World!</p>

</body>
</html>

现在,请看示例 3:

示例 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
在此示例中,我们添加了 id 选择器(名为“demo”)。文本现在将是 蓝色,因为 ID 选择器被赋予了更高的优先级:

<html>
<head>
  <style>    #demo {color: blue;}
    .test {color: green;}
    p {color: red;}  </style>
</head>
<body>

<p id="demo" class="test">Hello World!</p>

</body>
</html>

现在,请看示例 4:

示例 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
在此示例中,我们为 “p” 元素添加了内联样式。这 文本现在将为粉红色,因为内联样式被赋予了最高优先级:

<html>
<head>
  <style>    #demo {color: blue;}
    .test {color: green;}
    p {color: red;}  </style>
</head>
<body>

<p id="demo" class="test" style="color: pink;">Hello World!</p>

</body>
</html>

特异性层次结构

每个 CSS 选择器在特异性层次结构中都有其位置。

有四个类别定义了选择器的特异性水平:

  1. 内联样式 - 示例:\ <h1 style=“颜色:粉红色;”>
  2. ID - 示例: #navbar
  3. 类、伪类、属性选择器 - 示例:.test、 :悬停, [href]
  4. 元素和伪元素 - 示例:h1、::before

如何计算特异性?

记住如何计算特异性!

从0开始,为每个ID值加100,为每个值加 10,或为每个元素选择器或伪元素添加1。

注意: 内联样式获取特异性值 1000,并且 始终给予最高优先级!

注2: 有一个 此规则的例外情况:如果使用 !important 规则,它甚至会覆盖内联样式!

下表显示了有关如何计算特异性值的一些示例:

选择器 特异性值 计算
p 1 1
p.test 11 1 + 10
p#demo 101 1 + 100
<p style=“color: pink;”> 1000 1000
#demo 100 100
.test 10 10
p.test1.test2 21 1 + 10 + 10
#navbar p#demo 201 100 + 1 + 100
* 0 0

特异性值最高的选择器将获胜并生效!

请考虑以下三个代码片段:

1
2
3
A: h1  
B: h1#content
C: <h1 id="content" style="color: pink;">Heading</h1>

A的特异性为1(单元素选择器)
B的特异性为 101(一个 ID 引用 + 一个元素选择器)C 的特异性为 1000(内联样式)

由于第三条规则(C)具有最高的特异性值(1000),因此这种样式 将应用声明。

更多特异性规则示例

同等特异性:最新规则胜出 —— 如果将同一规则写入外部样式表两次,则 最新规则胜出:

1
2
h1 {background-color: yellow;}  
h1 {background-color: red;}


ID 选择器比属性选择器具有更高的特异性 - 查看以下三行代码:

1
2
3
div#a {background-color: green;}  
#a {background-color: yellow;}
div[id=a] {background-color: blue;}

第一条规则比其他两条规则更具体,因此将适用。

上下文选择器比单个元素更具体 selector - 嵌入的样式表更接近要设置样式的元素。所以在以下情况

1
2
3
4
5
6
7
8
/*From external CSS file:*/  
#content h1 {background-color: red;}

/*In HTML file:*/

<style>
#content h1 {background-color: yellow;}
</style>

将适用后一条规则。

类选择器可以胜过任意数量的元素选择器 - 类选择器(如 .intro)会胜过 h1、p、div 等:

1
2
.intro {background-color: yellow;}  
h1 {background-color: red;}