How can I tell CSS :not() selector to affect all child nodes?

两盒软妹~` 提交于 2020-12-27 06:36:01

问题


Please see this minimum example

.global :not(.guard) {
  color: red;
}
<div class="global">
  <p>I'm outside guard</p>

  <div class="guard">
    I'm inside guard.

    <div>
      <hr>

      <p>
        I'm a block inside guard.

      </p>

      <p>
        I want to black color too.
      </p>

      <p>
        How can I achieve it?
      </p>
    </div>
  </div>
</div>

I have a style(SCSS) like this

.global {
  :not(.guard) {
    color: red;
  }
}

I want anything inside the node with .guard class name's color not to be affected by color: red;

How can I achieve this effect?


回答1:


If I've correctly understood the effect you are trying to achieve, you can implement it with the following two selectors:

.global {
  color: red;
}

.global .guard {
  color: black;
}

In this case, you really don't need the :not() pseudo-selector at all.


Working Example:

.global {
  color: red;
}

.global .guard {
  color: black;
}
<div class="global">
  <p>I'm outside guard</p>

  <div class="guard">
    I'm inside guard.

    <div>
      <hr>

      <p>
        I'm a block inside guard.

      </p>

      <p>
        I want to black color too.
      </p>

      <p>
        How can I achieve it?
      </p>
    </div>
  </div>
</div>



回答2:


Since color is inherited, please use another rule for <p>:

.global :not(.guard) {
  color: red;
}

.global :not(.guard) p {
  color: black;
}
<div class="global">
  <p>I'm outside guard</p>

  <div class="guard">
    I'm inside guard.
    <div>
      <hr>
      <p>
        I'm a block inside guard.
      </p>
      <p>
        I want to black color too.
      </p>
      <p>
        How can I achieve it?
      </p>
    </div>
  </div>
</div>


来源:https://stackoverflow.com/questions/64909217/how-can-i-tell-css-not-selector-to-affect-all-child-nodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!