我发现 element
的选择器非常不合逻辑。里面 #id
优先于 #id
其中element
.
免责声明:我知道周围有很多类似的问题。我还阅读了 CSS 优先级和特殊性文档。然而,这些问题和文档似乎都没有涵盖我遇到的这个具体问题,更不用说解释原因了。也许我只是不擅长寻找;在这种情况下,请指导我。但我离题了。
例如,采用以下 HTML:
<style>
#top button {
padding: 0;
}
#myButton {
padding: 2em;
}
</style>
<header id="top">
<button type="button" id="myButton">Button</button>
</header>
由于某种原因,按钮没有填充。检查元素显示 #myButton
的样式被覆盖。
不是 #myButton
,它总是选择一个唯一的元素,比 #top button
更具体。 ,它选择一个唯一元素下的多个按钮?
这是一个错误还是一个预期的功能?这种行为在浏览器中的标准程度如何?如果是一项功能,为什么?
在 Windows 10 上使用 Chrome 78 和 Edge 44 (EdgeHTML 18) 进行测试。
最佳答案
基本上,#id1 元素
比 #id2
本身更具体。
特异性是累加性的,添加的越多(通常),选择器就越具体。
在您的示例中,#top
和 #button
具有相同的特异性,一旦您向其中一个选择器添加更多信息,它就会变得更加具体。因此,#top button
比 #button
本身更具体。
这是一篇关于 specificity 的精彩文章完成伟大cheat sheet .
举个例子,假设您有一个article
,您希望颜色为蓝色。但对于文章中的所有按钮
,您希望颜色为红色。
#article1 {color:blue;}
#article1 button {color:red;}
<article id="article1">
<p>The quick brown fox jumps over the lazy dog</p>
<button>Button</button>
</article>
实例中的一个选项是使用元素本身
#top button {
padding: 0;
color:red;
}
button#myButton {
padding: 2em;
color:blue;
}
<header id="top">
<button type="button" id="myButton">Button</button>
</header>
在此示例中,#top button
和 button#myButton
具有相同的特异性。但是,由于 button#myButton
最后声明,因此会应用它。
你也无意中发现了很多developers的原因之一。建议您不要使用 id 进行样式设置,而应该基本上使用类。
关于html - CSS 优先级奇怪 - "#id tag"> "#tagId"为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58722067/