【发布时间】:2017-08-08 02:51:54
【问题描述】:
所以我一直试图围绕 CSS 的特殊性来思考,在我看来,公式的工作方式是:
10^0 *(元素数量 + 伪元素选择器)+ 10^1 *(类数量 + 属性 + 伪类选择器)+ 10^2 *(id 选择器数量)+ 10^3 *(内联选择器)
因此,作为一个实验,我创建了一个 HTML 页面,其中有 12 个嵌套元素选择器应用于一些文本,以及一个类选择器。在这种情况下,许多元素选择器似乎应该覆盖单个类选择器,但它们没有。如果元素选择器获胜,此示例将文本呈现为红色,如果类选择器获胜,则呈现绿色。
发生了什么事?我误解了特异性公式吗?单个类选择器是否总是胜过任意数量的元素选择器?这就是为什么 id 选择器被认为是代码异味的原因,因为它们会覆盖任意数量的属性和类选择器?
html > body > main > article > section > form > div > figcaption > div > p > span > em {
color: red;
}
html body main article section form div figcaption div p span em {
color: red;
}
.test {
color: green;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
</head>
<body>
<main>
<article>
<section>
<form>
<div>
<figcaption>
<div>
<p>
<span>
<em class="test">TESTING 123</em>
</span>
</p>
</div>
</figcaption>
</div>
</form>
</section>
</article>
</main>
</body>
</html>
【问题讨论】:
-
快速阅读这篇文章:smashingmagazine.com/2007/07/…
标签: css css-selectors css-specificity