开发者

Can't figure out why CSS work like this

How come the #r3 isn't pink? (see jsfiddle.net/aAqKf/):

<!DOCTYPE HTML>
<html>
<head>
<style>
#r1 { width: 100px; height: 100px; border: solid 1px red; }
#r2 { width: 50px; height: 50px; border: solid 1px green; }
#r3 { width: 25px; height: 25px; border: solid 1px blue; }

.pink div {
    background: p开发者_JAVA百科ink;
}

.red div {
    background: red;
}
</style>
</head>
<body>

<div id="r1" class="red">
    <div id="r2" class="pink">
        <div id="r3"></div>
    </div>
</div>

</body>
</html>

I would expect the pink class to apply the pink background to the div children. It doesn't work like that. Why?

Though, it works if I change the CSS as follows (jsfiddle.net/aAqKf/1/):

<style>
#r1 { width: 100px; height: 100px; border: solid 1px red; }
#r2 { width: 50px; height: 50px; border: solid 1px green; }
#r3 { width: 25px; height: 25px; border: solid 1px blue; }

.red div {
    background: red;
}

.pink div {
    background: pink;
}
</style>

Please help me figure out how come it works that way. Also, please do not suggest that I use !important along with the background: pink declaration because it will work only until I change the HTML as follows:

<div id="r1" class="pink">
    <div id="r2" class="red">
        <div id="r3"></div>
    </div>
</div> 

NB: I am more interested in figuring out why it works that way than finding out how to make it work my way.


Both rules .pink div and .red div are equally specific. The latter rule overrides the former.

You almost never have to use !important, by the way. Using the selector body .pink div, or div.pink div is enough to give the selector more weight.


From this page

To make it easy, when two rules have the same weight, the last rule specified wins.

In your first fiddle, the red wins. In the second the pink wins.


Because the properties of class inheritance differ from that of the actual element.

For example, if you changed

.pink div { background: pink; }

to:

#r2 div { background: pink; }

it would work as you intended it, because the nested block level elements inherit based on their closest parent.

Classes, on the other hand, have much looser inheritance and properties get overwritten based on the parents, unless specifically said otherwise using !important, when two selectors have the same weight.

To further demonstrate this point, changing .pink div to div.pink div would also demonstrate the correct effect because, again, CSS is referring to an element and not a class selector.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜