Tigran Petrossian Tigran Petrossian - 1 month ago 6
CSS Question

LESS target every element of type unless it's within certain div

I'm looking for a neat way to solve the given problem:

Let's say we have an article, and I want to style every

h1
,
h2
in unless they are located in the
<div ="example">


<article class="article">
<h1>Direct Child 1</h1>
<h2>Direct Child 2</h2>

<div class="example">
<h1>Example Child 1</h1>
<h2>Example Child 2</h2>
</div>

<div class="other-div">
<h1>Indirect Child 1</h1>
<h2>Indirect Child 2</h2>
</div>
</div>


Now in pure CSS the solution is simple:

.article > h1,
.article *:not(.example) h1 {
color: red;
}

.article > h2,
.article *:not(.example) h2 {
color: blue;
}


All
h1
s are red, and
h2
s are blue, unless they're within
<div class=example>"
- Pen

In LESS, however, I can't find a clean way to do this.

.article {
& :not(.example) {
h1 {
color: red;
}

h2 {
color: blue;
}
}
}


I'm looking for a way to add
<div class=article>"
direct child
h1
s and
h2
into the mix while keeping it DRY.

Answer

I guess the main show-stopper for your attempt is the limitation of Less requiring a selector combinator (like >) to always go before a selector element (so neither & > nor > alone can work). There's workaround however:

.article {
    @-: ~'>'; 
    @{-}, *:not(.example) {
        h1 {color: red}
        h2 {color: blue}
    }
}