html - 了解 CSS 选择器优先级/特异性

标签 html css css-selectors

我想了解 CSS 选择器如何处理属性冲突。如何选择一种属性而不是另一种属性?

div {
  background-color: red;
}

div.my_class {
  background-color: black;
}

div#my_id {
  background-color: blue;
}

body div {
  background-color: green;
}

body>div {
  background-color: orange;
}

body>div#my_id {
  background-color: pink;
}
<div id="my_id" class="my_class">hello</div>

选择器优先级是如何工作的?

最佳答案

我将提供 CSS 2.1 规范本身的链接,以及浏览器应该如何计算特异性:

CSS 2.1 Section 6.4.3 :

A selector's specificity is calculated as follows:

  • count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
  • count the number of ID attributes in the selector (= b)
  • count the number of other attributes and pseudo-classes in the selector (= c)
  • count the number of element names and pseudo-elements in the selector (= d)
  • The specificity is based only on the form of the selector. In particular, a selector of the form "[id=p33]" is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source document's DTD.

Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.

如果特异性相等,则CSS 2.1 Section 6.4.1发挥作用:

  1. Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.

请注意,这是在定义样式时讨论的,而不是在使用样式时讨论的。如类.a.b具有相同的特异性,以样式表中最后定义的为准。 <p class="a b">...</p><p class="b a">...</p>将根据 .a 的定义顺序采用相同的样式和 .b .

关于html - 了解 CSS 选择器优先级/特异性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57563018/

相关文章:

html - 如何将 fontello 图标放入输入值中?

html - CSS calc() 在 IE 中无法与 em 一起正常工作

html - 如何在不设置父级默认高度的情况下添加包围绝对定位子级的轮廓

html - 如何更改 Eclipse 中 CSS 和 HTML 的默认设置

html - 悬停在超赞字体图标上时显示工具提示

javascript - 使用 Javascript 或 CSS,是否可以选择具有 css 样式溢出的元素 : hidden?

javascript - 优化 javascript 显示/隐藏单选表单选项

javascript - Jquery 文档.主体.背景

C# Selenium Web 驱动程序和 CSS : Start point

CSS选择第二个 child 从第二个开始