Question

I want to be able to change the background color of an anchor by applying a class to the anchor's parent div, and I need help with the syntax for the selector.

Here's my HTML, and there will be many links, so that's why I'd prefer to apply the class to the div rather than to each anchor within the div:

<div id="container">

    <div class="cell">
        <a href="#">should be green</a>
        <a href="#">should be green</a>
        <a href="#">should be green</a>
    </div>

    <div class="cell color2">
        <a href="#">should be red</a>
        <a href="#">should be red</a>
        <a href="#">should be red</a>
    </div>

</div>

Here's my CSS and the syntax of the color2 selector is wrong, and it doesn't change the background color of the color2 anchor:

div.color2 a {
    background: #f00; 
}

#container a {
    display:inline-block;
    float: left;
    height:14px;
    background: #0f0;
}
Was it helpful?

Solution

The specificity of your second selector is greater than your first one, so its styles will win out (this is the "cascade" in Cascading Style Sheets, btw). By virtue of that ID being in the selector, it will win out over any selector that contains only elements or classes. Try this:

#container div.color2 a {
    background: #f00; 
}

ref: http://css-tricks.com/specifics-on-css-specificity/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top