CSS - 特效性



想象一下,如果我们使用不同的选择器在 CSS 中多次声明一个属性会发生什么。CSS 使用**特效性**顺序来确定哪个选择器具有最高的优先级。

例如,如果使用类选择器和 ID 选择器在 HTML 元素上指定了两个或多个 CSS 规则,则在具有最高特效性值的选择器(在本例中为 ID 选择器)中声明的属性将应用于该元素。

specificity-order

特效性层次结构

CSS 中的每个**选择器**都具有一个特效性级别。以下是 CSS 选择器的特效性顺序。

  • **内联样式:** 使用 style 属性为元素定义的样式具有最高优先级。
  • <h1 style="color: blue;"> Example </h1>
  • **ID 选择器:** 在选择器中,ID 选择器具有最高优先级。
  • <style> #mainDiv { color: blue; } </style>
  • **类、属性和伪类:** 这些是下一个优先级。类选择器以句点 (.) 为前缀,属性选择器使用方括号 [],伪类以冒号(:) 为前缀。
  • <style> .subDivs { color: blue; } </style>
  • **元素和伪元素:** 这些具有最低的特效性。元素选择器直接使用元素名称,伪元素以双冒号 (::) 为前缀。
  • <style> div { color: blue; } </style>

如何计算特效性?

要计算特效性值,您需要记住这些值。内联样式的特效性值为 1000。ID 选择器的值为 100。对于类选择器、属性选择器和伪类,特效性值为 10。最后,对于元素选择器和伪元素,特效性值为 1。通配符选择器没有特效性值,为了比较的目的,我们可以认为其值为 0。

选择器 特效性 计算
<div style="color: green"></div> 1000 1000
#uniqueId 100 100
.mainClass 10 10
div 1 1
div #uniqueId 101 100+1
div .mainClass 11 10+1
div .mainClass .navbar 21 10+10+1
div #uniqueId .navbar 111 100+10+1

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

特效性规则示例

下面的示例代码将说明 CSS 特效性。

具有最高特效性值的选择器将生效

以下示例使用多个选择器将 color 属性应用于段落,在第一种情况下,ID 选择器生效,在第二种情况下,内联 CSS 生效。

Open Compiler
<!DOCTYPE html> <html> <head> <style> /*Multiple selectors for paragraph */ p { color: black; font-weight: bold; } .special { color: blue; } #unique { color: darkgreen; } </style> </head> <body> <p id="unique" class="special"> This paragraph will be darkgreen. Id selector wins!!!! </p> <p class="special"> This paragraph will be blue. Class selector wins!!!! </p> <p class="special" style="color: darkblue;"> This paragraph will be darkblue. Inline style wins!!!! </p> </body> </html>

 

特效性值相等,最新的规则获胜

以下示例显示,当两个类选择器目标相同的段落并尝试对其应用相同的样式时,最后定义的类将生效。

Open Compiler
<!DOCTYPE html> <html> <head> <style> p { color: black; font-weight: bold; } .special { color: blue; } .superSpecial{ color: gold; } </style> </head> <body> <p class="special superSpecial"> This paragraph is gold color. Class superSpecial wins!!! </p> </body> </html>

 

内部 CSS 样式优先于外部样式表

在 HTML 文档内使用 style 标签定义的选择器比外部导入的样式表具有更高的优先级。

/*From imported external CSS file:*/ #uniqueID { color: red; } /*In HTML file:*/ <style> #uniqueID { color: yellow; } </style>

元素将设置为黄色。

覆盖特效性规则

以下示例演示,如果属性标记为!important,则特效性顺序将变得无关紧要。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> p { color: black; font-weight: bold; } .special { color: blue; } #unique { color: darkgreen; } p { color: darkred !important; } </style> </head> <body> <p id="unique" class="special"> This paragraph is darkred. The !important keyword wins over every other selector!!! </p> <p class="special" style="color: green"> This paragraph is darkred. The !important keyword wins even over inline style!!! </p> </body> </html>
广告