As you know:
.blue p
matches any p tags within a .blue class.
.red p
matches any p tags within a .red class.
Your <p> first </p>
is within a blue class, so it matches the .blue p
rule, and is rendered as blue.
<div class="red">
is within both a red class and a blue class, so we have a dilemma. The way CSS resolves this is by using whichever rule appeared last. In this case the .blue p
rule appears last, and the text is rendered as blue.
CSS fix
If p tags are always going to be an immediate child of your color classes, you could do the following. The >
is a descendant selector that only matches immediate descendants.
.red > p {
color: red;
}
.blue > p {
color: blue;
}
CSS fix 2
You can also do as Tom suggested. The reason why it works is because CSS rules that are more specific will overwrite CSS rules that are less specific. Even though the blue rule comes second because div .red p
has two classes, it is more specific than .blue p
.
.red p,
.blue .red p {
color: red;
}
.blue p,
.red .blue p {
color: blue;
}
However, this only takes your problem one level deeper. The red class in the following HTML will still be rendered blue.
<div class="blue">
<div class="blue">
<p> first </p>
<div class="red">
<p> second </p>
</div>
</div>
</div>
HTML fix
This is the method I would suggest you use. You can simply move your classes to the p tags:
<div>
<p class="blue"> first </p>
<div>
<p class="red"> second </p>
</div>
</div>
Other items to watch out for
There are other ways a CSS rule can get overridden. I would suggest you research CSS specificity.
.red p
todiv.red p
or to.red > p
would increase the specificity of the rule so it would win over.blue p
.