I was playing with my CSS WordPress skin this weekend and had some trouble getting the color I wanted applied to certain <a> tags.
Here is the document structure:
<div id="rap">
<div id="content">
<div class="storycontent">
<p>Text here with an <a href="#">a tag</a>.</p>
</div>
<p><a href="#">Another text link here.</a></p> (adding this link)
</div>
</div>
</body>
The ‘.storycontent’ class sets both a light background color and the text color to black. The body background color is dark green. So I wanted the <a> tag in the <div class=".storycontent"> to be black and the <a> tag in the <p> tag below it (I was adding this tag) to be white. When I added the styling definition to turn the bottom link white, the link inside the <div class=".storycontent"> also turned white. This is not what I wanted.
I experimented with a number of combinations that I had expected to work but didn’t. Here are some examples.
I thought this would work, but it didn’t:
.storycontent p a {
color: black;
}
#content p a {
color: white;
}
</style>
This didn’t work. It looked like this:

Removing the p notation didn’t work either:
.storycontent a {
color: black;
}
#content a {
color: white;
}
</style>
This didn’t work either. It still looked like this:

#content .storycontent a {
color: black;
}
#content a {
color: white;
}
</style>
This finally worked:

I actually tried about a dozen or two permutations of this before finding the notation that worked.
My assumption is that in order to override a class, you need to define it from the same starting point (#content in this case). I think the ‘#content a’ definition ( applied to the <div id="content"> ) is inherited down through the <div class="storycontent"> to the <a> tag inside it. Trying to specify styling on the <a> tag inside the <div class="storycontent"> by declaring it from the ‘.storycontent’ level just wasn’t taking. When I declared it from the <div id="content"> level, it was applied as expected.
Can anyone verify or dispute this? It drove me nuts for about 20 minutes during the 49ers/Vikings game yesterday. 🙂
You can see it all in action here on my Golf site.
The rules precedence can be tricky. What I suspect is that those two rules had equal precedence scores, and in that case, the last rule defined gets used.
I bet that in the first example, if you reversed the order of the rules (define the ‘#content’ rule before the ‘.storycontent’ rule), it would work like you expect.
But as you found, another solution is to increase the specificity of the rules by including more selectors
I know that I’ve seen a pretty good explanation of the selector precedence rules by Eric Meyer, but I couldn’t find it.
Hi Dougal. I actually tried changing the order in which the rules were defined, but it had no effect in this case.
http://www.w3.org/TR[...]#specificity
http://www.meyerweb.[...]ificity.html
🙂