How do I write this: not a rule "in another element" CSS?
Here is the html layout
<div class="wrap">
<div class="section">
<span class="text">text1</span>
</div>
<span class="text">text2</span>
<span class="not-text">don't color me!</span>
</div>
I'm trying to style all "text" runs that are not in the "section" section. I tried this but it doesn't seem to work
.wrap :not(.section) .text
Any help is greatly appreciated!
Edit: There are several workarounds for this case, including using the> operator, for example in the ".wrap> .text" section, but I would like to know how to do: non-selector work, use it in the future
source to share
When you use .wrap :not(.section) .text
, this is what you say in the browser:
- Look for an element with a class
.text
- which lives inside an element that has no class
.section
- which lives inside an element that has a class
.wrap
If you take a close look at your markup, none of your elements will meet these selection criteria.
In the markup you provided, I don't think you can specifically highlight those elements .text
that are not descendants .section
using :not()
.
The closest you can get is to use a direct descendant selector, for example:
.wrap > .text
You can also select and mark all .text
descendants .wrap
(direct or not) and then undo those styles for any .text
elements inside .section
, for example:
.wrap .text {
// your styles here
}
.wrap .section .text {
// your cancelled styles here
}
source to share
The best option, given the limitations of CSS, is to write a rule for all text and then override them back to the previous value for those inside the .section. So
.wrap .text {
// the styles you want
}
.wrap .section .text {
// styles undoing the styles above... depending on what the styles are it may not always be possible
}
source to share