
CSS特异性,是一种根据点数区分不同CSS选择器或优先级的过程,具有最高特异性点数的选择器将获胜,并且该选择器的CSS样式将应用于该元素。
每个 CSS 选择器的点层次结构及其优先级如下表所示 -
| Sr. No. | 的中文翻译为:序号 | CSS选择器 | 特异性得分 |
|---|---|---|---|
| 1 | 元素选择器 | 1 | |
| 2 | 类选择器 | 10 | |
| 3 | ID选择器 | 100 | |
| 4 | 内联CSS | 1000 | |
| 5 | 元素+类选择器 | 1 + 10 = 11 | |
| 6 | 元素+ID选择器 | 1 + 100 = 101 |
用例 − 假设你有一个带有类和ID的元素,并且你想要使用类选择器和ID选择器给它添加CSS样式。在这种情况下,它将使用ID选择器定义的CSS样式,因为ID选择器的特异性比类选择器高10倍。
现在让我们借助代码示例详细了解这些选择器之间的区别及其优先级。
立即学习“前端免费学习笔记(深入)”;
步骤 1 - 在第一步中,我们将定义一个带有类和ID属性的HTML元素。
第二步 - 在这一步中,我们将通过使用CSS选择器选择元素并检查它们的优先级,为元素编写CSS。
下面的示例将说明不同 CSS 选择器之间的差异及其优先级 -
<html>
<head>
<style>
/* CSS of the main Div using Class = 10 points and ID = 100 points selectors */
#IdDemo {
background-color: #84abb5;
color: white;
height: 150px;
text-align: center;
}
.classDemo {
background-color: green;
color: white;
height: 400px;
text-align: end;
}
/* Heading Styles to show difference between only class = 10 points and element + class selector = 11 points */
h2.demoH2Class {
color: #e6d4b6;
background-color: #414141;
}
.demoH2Class {
color: red;
background-color: white;
}
</style>
</head>
<body>
<div id = "IdDemo" class = "classDemo">
<h2 class = "demoH2Class" id = "demoH2ID"> This is Heading of Demo element. </h2>
</div>
</body>
</html>
在上面的示例中,我们通过在两个不同的选择器的帮助下选择同一个元素,在同一个元素上使用了相同的 CSS 属性,我们可以清楚地看到具有较高特异性点的选择器的 CSS 应用于该元素。
下面的示例将解释更多 CSS 选择器在其特殊点方面的差异 -
<html>
<head>
<style>
/* CSS of the main Div using and element + ID = 101 points selectors */
div#IdDemo {
background-color: green;
color: blue;
height: 250px;
text-align: start;
}
/* Heading Styles to show difference between only ID = 100 points and element + ID = 101 points selector */
h2#demoH2ID {
color: #e6d4b6;
background-color: #414141;
}
#demoH2ID {
color: red;
background-color: white;
}
</style>
</head>
<body>
<!-- CSS of the main div is given inline = 1000 points and inside the ID + element = 101 points -->
<div id = "IdDemo" class = "classDemo"
style = "background-color: #84abb5; color: white; height: 150px; text-align: center;">
<h2 class = "demoH2Class" id = "demoH2ID">This is Heading of Demo element.</h2>
</div>
</body>
</html>
在上面的例子中,我们再次使用了相同的CSS属性,但在不同的CSS选择器中使用了不同的值。在主div元素的情况下,我们使用了内联和ID选择器来应用CSS,但由于内联选择器的优先级远远高于ID选择器,所以内联CSS被应用到了该元素上。而在h2标题的情况下,我们使用了ID和元素+ID选择器,后者的CSS特异性更高,因此元素+ID选择器的CSS被应用到了该元素上。
在本文中,我们不仅学习了CSS特异性点的计算,还详细了解了不同CSS选择器内部编写的CSS的优先级与其特异性点之间的区别,并通过代码示例进行了实际操作。我们通过同时选择不同选择器来为同一元素赋予不同值的CSS属性,从而看到了CSS选择器之间的差异。
以上就是CSS特异性的分数是如何计算的?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号