【问题标题】:Use :not selector to exclude a div and all its descendants使用 :not 选择器排除 div 及其所有后代
【发布时间】:2016-06-25 01:17:38
【问题描述】:

我有一种情况,需要将带有浅黄色背景的紫色字体颜色样式应用于具有RadDiv 类的 div 之外的所有 div。

这意味着所有嵌套在 div 中的类为 RadDiv 的 div 都应该被排除。

我尝试使用:not 选择器,如下所示,但它不起作用。 Demo of my situation

问题:如何指定:not 选择器以排除具有RadDiv 类的div 以及该div 内的所有嵌套div?

:not 选择器不起作用

div:not(.RadDiv) div   {
  background-color:lightyellow;
  color:purple;
  }

我尝试过的完整代码

<div>This is a div </div>
<div class="RadDiv newDiv outerDiv">
    <div class="header">
      This is the header
    </div>

     This is an outer div

     <div class="alert highlight">
      This div stands out
    </div>
    <div class="footer disclaimer">
     This is the footer part
    </div>
    <table>
      <tr>
       <td>
         <div>This is div inside a table element</div>
       </td>
      </tr>
    </table>
</div>
<div id="div1">This is div1</div>
<div id="div2">This is div2</div>
<style>
div:not(.RadDiv) div   {
  background-color:lightyellow;
  color:purple;
  }
  .outerDiv {
      border:1px solid red;
      font-family:Arial;
  }
  .footer {
    color:lightgray;
    font-size:small;
    font-style:italic;
    }
    .header {
    font-weight:bold;
    }

【问题讨论】:

  • 试试这个:div:not(.RadDiv div)
  • 我刚试了下还是不行。

标签: html css css-selectors


【解决方案1】:

:not 选择器没有那么强大,并且在更复杂的情况下它不会按照您希望的方式工作。实现您想要的最简单的方法可能是覆盖 .RadDiv 样式:

div {
  background-color:lightyellow;
  color:purple;
  }
.RadDiv, .RadDiv div {
  background: transparent;
  color: black;
}

【讨论】:

    【解决方案2】:

    将所有同级别的 div 视为同级。因此,首先选择父项:

    body > div:not(.RadDiv) {
        background-color: lightyellow;
        color: purple;
    }
    

    使用子组合器 (&gt;),只定位一个级别,:not 选择器可用于排除任何同级(包括其后代)。

    Revised Fiddle

    参考资料:

    【讨论】:

    • 这是有道理的。 So, the trick is to find the parent of all divs 。另外,如果我在 RadDiv 之外有 span 元素,那么它们也将被设置为紫色字体,即使我只希望 div 被设置为紫色字体。
    • 没有。我的答案中的选择器仅针对 div 元素。
    • 如果您在同一级别有不同的元素,并且您希望它们全部定位RadDiv 除外,您可以将选择器调整为:body &gt; *:not(.RadDiv)
    • 好的。我现在明白了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2022-01-23
    • 2012-05-20
    • 1970-01-01
    相关资源
    最近更新 更多