views:

188

answers:

2

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"&gt;
                stackoverflow
            </a>
        </div>
    </body>
</html>

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

+5  A: 

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"&gt;
                stackoverflow
            </a>
        </div>
    </body>
</html>
Obalix
+5  A: 

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

Scott Cranfill