Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target a selector only if it's NOT child of a specific element (so only if it's the root)

I don't understand why the following code has not desired behaviour:

    .toggle {
      color: red;
    }
    
    :not(.list) .toggle {
      font-weight:bold;
    }
  <div class="container">
      <a href="#!" class="toggle">Toggle</a>
      <ul class="list">
        <li><a href="#!">Link 1</a></li>
        <li>
          <div class="container">
            <a href="#!" class="toggle">SubToggle</a>
            <ul class="list">
              <li><a href="#!">SubLink 1</a></li>
              <li>
                <a href="#!">SubLink 2</a>
              </li>
              <li><a href="#!">SubLink 3</a></li>
            </ul>
          </div>
        </li>
        <li><a href="#!">Link 3</a></li>
      </ul>
    </div>

I thought that using :not() would result in applying "bold" only to main "Toggle" link but instead it applis "bold" to all of red ones. Why?

Please, note that this code is nested with same class names, I don't want to target specific levels with different css classes, I would like to target elements only with descendant selectors and other operators

Here is present also a jsFiddle to directly try.

like image 446
Luca Detomi Avatar asked Oct 24 '16 09:10

Luca Detomi


2 Answers

I think you might want this:

.toggle {
  color: red;
  font-weight: bold;
}

div *:not(.list) .toggle {
  font-weight: normal;
}
like image 131
Mike Harrison Avatar answered Nov 15 '22 23:11

Mike Harrison


I tried so many times but this is the only way I can do:

.toggle {
  color: red;
  font-weight:bold;
}

.list .toggle{
  //override
  font-weight:normal;
}

This is how to use :not the right way: add specialToggle for elements you do not want to select

<a href="#!" class="toggle specialToggle">SubToggle</a>

and then css:

.toggle {
  color: red;
}

.toggle:not(.specialToggle) {
  font-weight:bold;
}

https://jsfiddle.net/s249tyur/3/

like image 27
Jared Chu Avatar answered Nov 15 '22 23:11

Jared Chu