【问题标题】:Not getting correct output by :not() pseudo class:not() 伪类没有得到正确的输出
【发布时间】:2020-06-17 03:37:33
【问题描述】:

div:not(.awesome) {
  color: red;
}

 :not(div) {
  color: blue;
}
<div>Selected for 1st</div>
<div class="awesome">Not selected</div>
<section>This is selected for 2nd</section>
<section>This is selected for 2nd</section>

现在浏览器以红色显示 html 的第一行,其余三行以蓝色显示。但我认为第二行不应该涂成蓝色,因为它的类值“真棒”而且它是元素。所以这违反了我在css中写的两条规则。因此,它不应该被样式化。有人可以帮忙吗?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    添加边框以注意:not(div) 也在选择bodyhtml 元素。您的第二个元素未被选中,而是继承来自正文的颜色。

    您可以清楚地注意到第二个div 周围没有边框:

    div:not(.awesome) {
      color: red;
    }
    
     :not(div) {
      color: blue;
      border:1px solid
    }
    <div>Selected for 1st</div>
    <div class="awesome">Not selected</div>
    <section>This is selected for 2nd</section>
    <section>This is selected for 2nd</section>

    为 body 定义一个颜色以获得另一个结果:

    div:not(.awesome) {
      color: red;
    }
    
     :not(div) {
      color: blue;
      border: 1px solid
    }
    
    body {
      color: green
    }
    <div>Selected for 1st</div>
    <div class="awesome">Not selected</div>
    <section>This is selected for 2nd</section>
    <section>This is selected for 2nd</section>

    在应用选择器时最好考虑使用包装器,以确保您的选择范围明确定义并且您不会选择不需要的元素。您可以使用 body 元素,但不推荐使用,因为即使是 the body can give you some surprise.

    .container div:not(.awesome) {
      color: red;
    }
    
    .container :not(div) {
      color: blue;
      border: 1px solid
    }
    <div class="container">
      <div>Selected for 1st</div>
      <div class="awesome">Not selected</div>
      <section>This is selected for 2nd</section>
      <section>This is selected for 2nd</section>
    </div>

    【讨论】:

    • 很好的解释。为了解决这个问题,他可以使用body :not(div) 选择器
    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    相关资源
    最近更新 更多