每个 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。
example的中文翻译为:示例下面的示例将说明不同 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 应用于该元素。
示例 2下面的示例将解释更多 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特异性的分数是如何计算的?的详细内容。
