详情
我在 FirefoxDeveloperEdition 中工作并遇到意外的选择器优先级。我已经阅读了 Smashing Magazine article "CSS Specificity: Things You Should Know"并且,据我所知,已经构建了 CSS 选择器,以便为每个选择器实现预期的特异性水平。但是,错误的声明正在被取消。
这里有什么问题?我还没有完全了解选择器特异性的工作原理吗?这是一个错误吗?或者,还有什么?
元素代码(简体)
/index.html
<head>
<link href="css/style.css">
</head>
<body>
<section class="hud">
<section class="main float-l">
<a href="#0" class="button">
<div class="outer container">
<div class="inner container">
<p class="show"> <!-- This text is meant to be white by the style declared at line 159. But, it's grey by line 61. -->
View Details
</p>
<div class="arrow"></div>
<p class="hide"> <!-- This text is meant to be white by the style declared at line 159. But, it's grey by line 61. -->
Hide Details
</p>
</div>
</div>
</a>
</section>
</section>
</body>
/css/style.css
58 .hud > .main p /* I also tried `.hud > .main p:not(.button)` */
59 {
60 vertical-align: middle;
61 color: #7C7C7C; /* This grey is applied of the white of line 159. */
62 {
...
155 .hud > .main > .button
156 {
157 display: block;
158 background-color: #986B99;
159 color: #FFFFFF; /* This white should be applied, but is overridden by the grey of line 61. */
160 height: 36px;
161 margin: 20px 10px 10px;
162 padding: 8px 20px;
163 font-weight: 400;
164 text-decoration: none;
165 text-transform: uppercase;
166 border-radius: 2px;
167 }
检验员
尝试过 .hud > .main > .button
与 .hud > .main p
还尝试了 .hud > .main > .button
与 .hud > .main p:not(.botton)
最佳答案
这是因为第一个样式与元素匹配,第二个样式继承自其父元素。
只有当两个选择器匹配同一个元素时,特异性才会发挥作用。当涉及到从父元素继承样式时,情况并非如此。
你可以在非常简单的例子中看到这一点:
#myID {
color: red;
}
p {
color: green;
}
<div id="myId">
<p>Some text</p>
</div>
即使 #myId
更具体,文本是绿色的,因为 p
选择器直接匹配该元素,因此比继承自的 color
更重要div
.
要使 .button
中的 p
元素变为白色,您需要:
.hud > .main > .button p {
color: #fff;
}
关于CSS 选择器级联/特异性未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27804589/