开发者

CSS specificity / priority based on order in style sheet?

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"&开发者_如何学运维gt;
      I would like this to be red
    </div>
  </div>
</div>


You can use the E > F child selector as a solution to your problem as such:

div.green_colour > div.has_colour{
  background-color: green;
}
div.red_colour > div.has_colour{
  background-color: red;
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜