<html><head><style type="text/css">
#foo { color: blue; }
a.bar { color: red; }
#foo .baz { background-color: cyan; }
a.bar > .baz { background-color: yellow; }
</style></head>
<body>
<div id="foo">
<a href="#" class="bar">
<span class="baz">TEXT</span>
</a>
</div>
</body>
</html>
I’m a CSS noob, but my intuition tells me that a.bar is a more specific match for the <span> containing TEXT than #foo, and that TEXT should appear in red with a yellow background. Or if #foo is more specific, then TEXT should be in blue with a cyan background.
Instead, TEXT appears (as tested on Chrome, IE8) in red with a cyan background. How is it that a.bar is more specific than #foo, but #foo .baz is more specific than a.bar > .baz? How would I get this text to appear with red and cyan yellow with the least disruption (smallest set of changes) to the styles I have already specified?
What you’re seeing with the text color doesn’t have to do with which selector is applied. Both selectors are being applied, but to different elements. Translated to inline styles your CSS would look like:
background-color: yellow;was overridden by the more specific selector, but your other selectors don’t override each other. They apply to different elements. The span will inherit thecolorfrom it’s closest ancestor which has a specified value forcolor. In this case that is the<a>.If you want a yellow background with minimal changes I would suggest making that selector have higher specificity by prepending
#fooonto it like#foo a.bar > .baz. Here is a JSFiddle demo.