CSS 特异性/优先级基于样式表中的顺序?
我简要浏览了 CSS3 选择器规范,但无法找到任何方法来解决这个问题。此外,当您移动 CSS 声明时,我并没有预料到结果会发生变化,但事实确实如此。任何帮助都会很棒。
div.green_colour div.has_colour{
background-color: green;
}
div.red_colour div.has_colour{
background-color: red;
}
<div class="red_colour">
<div class="green_colour">
<div class="has_colour">
I would like this to be green
</div>
</div>
</div>
<div class="green_colour">
<div class="red_colour">
<div class="has_colour">
I would like this to be red
</div>
</div>
</div>
I had a brief look at the CSS3 Selectors spec but couldn't find anything how to get round this problem. Additionally, I wasn't expecting the result from this to change when you move the CSS declarations around but it does. Any help would be great.
div.green_colour div.has_colour{
background-color: green;
}
div.red_colour div.has_colour{
background-color: red;
}
<div class="red_colour">
<div class="green_colour">
<div class="has_colour">
I would like this to be green
</div>
</div>
</div>
<div class="green_colour">
<div class="red_colour">
<div class="has_colour">
I would like this to be red
</div>
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
E >; F
子选择器作为您问题的解决方案,如下所示:根据此图表 http:// /www.quirksmode.org/css/contents.html 它与所有主要浏览器和 IE 7+ 兼容
。如果您有兴趣,还有其他方法可以实现上述解决方案(例如通过 javascript)。
-- 编辑:
我不能 100% 确定您的解决方案不起作用的原因是否是由于浏览器从右到左而不是从左到右解析 CSS,但我认为这与此有关。如果我错了,请有人纠正我。
You can use the
E > F
child selector as a solution to your problem as such:According to this chart http://www.quirksmode.org/css/contents.html it is compatible with all major browsers and IE 7+
There are other ways to implement the solution above (e.g. via javascript) if you are interested.
-- Edit:
I'm not 100% sure if the reason for your solution not to work is due to the fact that browsers parse CSS from right to left instead of left to right, but I assume it has something to do with it. Someone please correct me if I'm wrong.