Urbycoz
Urbycoz

Reputation: 7421

How do I set a style but exclude classes and their children?

I have less which is styling a div on my page. I'd like to create some less to exclude divs with a particular class, along with all their children.

Here's my (simplified) html:

<div class='people'>
    <div>
        <!--This text should be green-->
        Bob
    </div>
    <div>
        <!--This text should be green-->
        Geoff
    </div>
    <div class="ex-members">
        <div>
            <!--This text should remain red--> 
            Mary
        </div>
        <div>
            <!--This text should remain red--> 
            Fred
        </div>
    </div>
</div>

Here's the less I'm trying to use:

body {
   color:red;
}
.people {
   &:not(.ex-members) {
      color:green;
   }
}

But this seems to just set all the names to green.

N.B. I could of course solve this by overwriting the green color and setting ex-members back to black again, but I'd like to avoid doing this if possible.

Upvotes: 1

Views: 960

Answers (2)

Joseph Webber
Joseph Webber

Reputation: 2173

Your ex-members div is inside your people div, and your second style is looking for elements with a people class and no ex-members class on them. The simple solution is to just remove the &:not.

.ex-members {
  color:green;
}

Upvotes: 0

Paulie_D
Paulie_D

Reputation: 115293

You could use a direct descendant selector >

.people {
   > :not(.ex-members){
      color:green;
   }
}

which compiles to...

body {
  color: red;
}

.people> :not(.ex-members) {
  color: green;
}
<div class='people'>
  <div>
    <!--This text should be green-->
    Bob
  </div>
  <div>
    <!--This text should be green-->
    Geoff
  </div>
  <div class="ex-members">
    <div>
      <!--This text should remain red-->
      Mary
    </div>
    <div>
      <!--This text should remain red-->
      Fred
    </div>
  </div>
</div>

Upvotes: 2

Related Questions