YIXUNFE / blog

文章区
151 stars 25 forks source link

CSS样式层叠和优先级 #9

Open masterkong opened 8 years ago

masterkong commented 8 years ago

CSS样式层叠和选择器特殊性

CSS样式层叠

浏览器根据层叠和继承规则确定显示一个元素时各种样式属性采用的值。对于每一个这种属性,浏览器都需要查看一下其所有的样式来源。

由浏览器定义的样式称为浏览器样式或者叫用户代理样式

用户通过浏览器应用自己的样式(比如调整网页的字号和字体),称为用户样式。 网站开发者提供的样式(元素内嵌样式、文档内嵌样式和外部样式表)合称为作者样式

最后把样式属性值标记为重要(!important),可以提升重要性。

因此,层叠采用以下重要度次序(排名越前越重要)

如果有两条定义于同一层次的样式都能应用于同一个元素,而且它们都包含着浏览器要查看的CSS属性,这时浏览器会评估两条样式的具体程序,然后选中较为特殊的那条。 选择器特殊性也称为选择器优先级、选择器权重。

以下引用MDN关于特殊性的定义

The specificity is a weight that is applied to a given CSS declaration based on the count of each selector type. In the case of specificity equality, the latest declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted. CSS rules that directly target an element will always take precedence over rules that an element inherits from an ancestor.

选择器的特殊性分成4个成分等级:a、b、c和d

特殊性示例

选择器 特殊性 以10为基数的特殊性
Style= "" 1,0,0,0 1000
#wrapper #content {} 0,2,0,0 200
#content .datePosted {} 0,1,1,0 110
div#content {} 0,1,0,1 101
#content {} 0,1,0,0, 100
p.comment .dateposted {} 0,0,2,1 21
p.comment {} 0,0,1,1 11
div p {} 0,0,0,2 2
p {} 0,0,0,1 1

几种特殊情况的处理

ID属性选择器 *[id="foo"]

Specificity is based on the form of a selector. In the following case, the selector *[id="foo"] counts as an attribute selector for the purpose of determining the selector's specificity, even though it selects an ID.

按属性选择器计算,即使它是通过ID属性来定位的

* #foo {
  color: green;
}
*[id="foo"] {
  color: blue;
}

<p id="foo">The text color is green.</p>

否定选择器 :not

The negation pseudo-class :not is not considered a pseudo-class in the specificity calculation. But selectors placed into the negation pseudo-class count as normal selectors when determining the count of selector types.

否定选择器不作为伪类选择器计算权重,便否定选择器内部的选择器按正常情况处理

div.outer p {
  color:green;
}
div:not(.outer) p {
  color: blue;
}

<div class="outer">
  <p>The text color is green.</p>
  <div class="inner">
    <p>The text color is blue.</p>
  </div>
</div>

直接定位元素的样式比继承来的样式更特殊

Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.

#parent {
  color: green;
}
h1 {
  color: blue;
}

<div id="parent">
  <h1>The text color is blue.</h1>
</div>

参考文献