Reputation: 1
I'm trying to create a CSS layout where I use a set of classes to determine the colour scheme of elements and their contents.
I've run into a bit of a problem regarding cascading (I think) - this seems like a really elementary problem to me but I just can't figure out a simple way of doing it.
.red-content p {
color: red;
}
.blue-content p {
color: blue;
}
<div class="blue-content">
<div class="inner">
<p>Blue</p>
</div>
<div class="red-content">
<div class="inner">
<p>Red</p>
</div>
</div>
</div>
Here's a Codepen that illustrates the problem I am having: https://codepen.io/tomhayes/pen/OJVqKoo
Basically, the blue text should be blue, and the red text should be red, but the rules are conflicting and making all of the text blue.
I can't use the order of the CSS rules to achieve this because the order of the elements will change, and I am trying to avoid needing to use >
because the elements will sometimes have to be nested several levels deep.
Upvotes: 0
Views: 1004
Reputation: 371241
You can add a bit of specificity to your red class.
.red-content:not(.blue-content) p {
color: red;
}
.blue-content p {
color: blue;
}
<div class="blue-content">
<div class="inner">
<p>Blue</p>
</div>
<div class="red-content">
<div class="inner">
<p>Red</p>
</div>
</div>
</div>
§ 4.3. The Negation (Matches-None) Pseudo-class:
:not()
The
:not()
pseudo-class allows useless selectors to be written.For instance
:not(*|*)
, which represents no element at all, ordiv:not(span)
, which is equivalent todiv
but with a higher specificity.
Upvotes: 1
Reputation: 634
Do you need to specify this for paragraphs only? If not...
.red-content {
color: red;
}
.blue-content {
color: blue;
}
<div class="blue-content">
<div class="inner">
<p>Blue</p>
</div>
<div class="red-content">
<div class="inner">
<p>Red</p>
</div>
</div>
</div>
Upvotes: 1
Reputation: 9
Check the placement of the div's, you were missing one for the blue-content, and it was overriding the red-content.
I have added some indentation to help highlight the structure.
<div class="blue-content">
<div class="inner">
<p>Blue</p>
</div>
</div>
<div class="red-content">
<div class="inner">
<p>Red</p>
</div>
</div>
Upvotes: 0