CSS 解释specificity的概念
specificity 是HTML浏览器用来定义应用于HTML元素的最合适的CSS声明的一个高级算法。它基本上计算所有CSS选择器的权重,以确定适当的规则。其主要目的是当多个CSS规则应用于同一个元素时,将应用具有最高 specificity 值的选择器到该元素。
specificity 的计算:
specificity 计算适用于给定CSS声明的权重。该算法基本上是一个由四个不同类别组成的四列值——行内类、ID、类和元素。这些值表示每个类别中每个选择器的计数。
| RANKS | SELECTOR |
|---|---|
| 0.0.0.0 | Universal Selector (*) |
| 0.0.0.1 | Element or Pseudo-element |
| 0.0.1.0 | Class or Pseudo Class or data attribute |
| 0.1.0.0 | ID |
| 1.0.0.0 | Inline Style |
从这张图中,我们可以得出以下结论:在底部 specific rank 最大,在顶部最小。
因此,least specific rank = (0.0.0.0),most specific rank = (1.0.0.0)。基于此图,将计算specific ranks,并选择具有最高specific rank 的CSS声明来应用到该元素。
示例1: 在这个示例中,我们为同一个锚点元素应用了几个CSS规则。将应用具有最高specificity 的规则。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Css Specificity</title>
<style>
/* Inline class=0, ID=0, class=0, element=1
So, specificity rank =0.0.0.1 */
* a {
color: rgb(115, 255, 0);
}
/* Inline class=0, ID=1, class=0, element=0
specificty =0.1.0.0
This is the highest specificity rank,
so this will be applied */
#links {
color: blueviolet;
}
/* Inline class=0, ID=0, class=0, element=1
specificty =0.0.0.1 */
a {
color: pink
}
/* Inline class=0, ID=0, class=1, element=1
specificty =0.0.1.1 */
.text a {
color: brown;
}
</style>
</head>
<body>
<div>
<h1 style="color: green;">GeeksforGeeks</h1>
<div class="text">
This is the best platform for Coding.<br>
<a href="www.geeksforgeeks.com" id="links">Click the Link</a>
</div>
</div>
</body>
</html>
输出:

示例2: 有一个属性 !important ,通过应用于任何CSS规则,使其成为应用于元素的值。让我们看一个示例。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Css Specificity</title>
<style>
* a {
color: rgb(115, 255, 0);
}
#links {
color: blueviolet;
}
a {
color: pink;
}
/* Although this has lower specificity ranks
but applying !important to override */
.text a {
color: brown !important;
}
</style>
</head>
<body>
<div>
<h1 style="color: green;">GeeksforGeeks</h1>
<div class="text">
This is the best platform for Coding.<br>
<a href="www.geeksforgeeks.com"
id="links">Click the Link</a>
</div>
</div>
</body>
</html>
输出:

注意: 可以看到,使用 !important 覆盖了特异性,所以现在在锚点标签上应用了褐色。但是,如果另一个选择器也附加了!important标记到相同的属性上,则将使用最后一个的值。因此,在CSS中使用这种方式被认为是一种不好的实践,因为很难覆盖样式。
参考资料: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
极客教程