【问题标题】:Can't add multiple pseudo-classes to a :not() pseudo-class不能向 :not() 伪类添加多个伪类
【发布时间】:2020-10-19 00:48:43
【问题描述】:

我尝试将样式应用于除第一个和最后一个元素之外的每个元素。我知道有很多方法可以做到这一点。但我正面临一种奇怪的行为(我相信?)。

如果我使用 :not() 伪类与 :last-child 关联,例如,它会正常工作。但是一旦我添加了第二个伪类(比如说:first-child),它就不起作用了。

我们来了

.div-list {
  width:100px;
  height:400px;
}

.div-list div {
  width:25%;
  height:25%;
  background-color:green;
}
.div-list div:not(:last-child) {
  background-color:red;
}

.div-list div:not(:last-child,:first-child) {
  border:1px solid blue;
}
<div class='div-list'>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

请注意,我知道standard,显然我的语法“理论上”是正确的。我错了吗?

【问题讨论】:

    标签: html css css-selectors pseudo-class


    【解决方案1】:

    :not 的多个类选择器仅在 CSS 选择器级别 4 中受支持,并且它不适用于所有浏览器。它目前仅适用于Safari,您可以使用多个:not

    .div-list div:not(:last-child):not(:first-child) {
      border:1px solid blue;
    }
    

    查看browser support doc

    【讨论】:

    • 这是有道理的。我知道 :not() 中的多个选择器没有得到很好的支持,我不知道它是如此先进以至于它在任何地方都不受支持哈哈。谢谢你这么清楚的回答。
    【解决方案2】:

    宁可使用这个选择器,它使用 2 个非选择器,这就像说不是最后一个孩子而不是第一个孩子:

    .div-list div:not(:last-child):not(:first-child)
    

    .div-list {
      width: 100px;
      height: 400px;
    }
    
    .div-list div {
      width: 25%;
      height: 25%;
      background-color: green;
    }
    
    .div-list div:not(:last-child) {
      background-color: red;
    }
    
    .div-list div:not(:last-child):not(:first-child) {
      border: 1px solid blue;
    }
    <div class='div-list'>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-03
      • 2023-03-22
      • 2011-08-06
      • 1970-01-01
      • 2018-08-24
      相关资源
      最近更新 更多