开发者

CSS Inheritance: Overriding a parent selector that is a descendant selector

How can I make this link use the child selector without changing or removing the parent selector? (I want the link to be blue.)

<html>
    <head>
        <style>
            .parent a { color:Red; }
            .child { color:Blue; }
        </style>
    </head>
    <body>
        <div class="parent">
            <a class="child"开发者_开发技巧 href="http://www.stackoverflow.com">
                stackoverflow
            </a>
        </div>
    </body>
</html>

It is surprising to me that the parent overrides the child in this case!


Use a.child as the selector.

<html>
    <head>
        <style>
            .parent a { color:Red; }
            a.child { color:Blue; }
        </style>
    </head>
    <body>
        <div class="parent">
            <a class="child" href="http://www.stackoverflow.com">
                stackoverflow
            </a>
        </div>
    </body>
</html>


This is due to CSS specificity. The extra a after .parent makes it more specific than just .parent, and correspondingly, more specific than just .child. Obalix's suggestion gives the selectors the same specificity, with both having a base HTML element and a class designation. When specificity is equal, it will then apply the deepest value specified in the hierarchy, as you were expecting.

This article (and the resources to which it links) do a great job explaining CSS specificity: http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html


For future exploring http://css-tricks.com/specifics-on-css-specificity/

basically you can count selectors value in this order

Inline | ID | Class/pseudoclass | Element
1      | 1  | 1                 | 1

where Inline = 1000, ID = 100, Class = 10, Element = 1

In your case .parent a == 11 and .child == 10 thats why parent overrides child element style.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜