PHP前端开发

CSS特异性的分数是如何计算的?

百变鹏仔 4周前 (09-19) #CSS
文章标签 特异性

CSS特异性,是一种根据点数区分不同CSS选择器或优先级的过程,具有最高特异性点数的选择器将获胜,并且该选择器的CSS样式将应用于该元素。

每个 CSS 选择器的点层次结构及其优先级如下表所示 -

的中文翻译为:
Sr. No.序号CSS选择器特异性得分
1元素选择器1
2类选择器10
3ID选择器100
4内联CSS1000
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选择器之间的差异。