【问题标题】:Select all of one element except a few using :not(selector) [duplicate]使用 :not(selector) 选择除少数之外的所有元素 [重复]
【发布时间】:2018-10-19 08:03:00
【问题描述】:

我正在尝试选择除前 3 个之外的所有“类”类。我不确定为什么我的语法不正确。有人可以解释我在这里做错了什么吗?

我尝试了一些不同的组合,例如在选择器中包含第 n 个类型之前的类名等。

.classes {
  background: red;
  width: 200px;
  height: 30px;
  margin-bottom: 5px;
}

.classes:not(.classes:nth-of-type(1)), .classes:not(nth-of-type(2)), .classes:not (nth-of-type(3)) {
  background: blue;
}

.classes:nth-of-type(6) {
  background: orange;
}
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>

【问题讨论】:

  • not() 只取简单的选择器
  • 你可以试试这个:jsfiddle.net/nn3mso3x 但要注意,因为它考虑的是元素而不是类

标签: html css css-selectors


【解决方案1】:

你可以用这个:

.classes {
    background: green;   
}
.classes:nth-child(n+4) {
    background: red;
}

你可以找到更多有用的:nth-child例子here

如果你想完全使用 :not 选择器,你可以试试这个:

.classes:not(:first-child):not(:nth-child(2)):not(:nth-child(3)) {
  background: yellow;
}

【讨论】:

  • 这不是通用的方式,也不会一直有效...取决于结构
  • 它会选择除前 3 个之外的所有类,如问题中所述。
  • 不,它选择从具有 .classes 的第四个元素开始的所有元素......所以在这种情况下这是有效的,因为所有元素都具有相同的类,但它不是通用的......您可以简单地执行nth-child(n+4) 的方式,它也将执行相同的操作
  • 我喜欢你的解决方案!但是说如果我不想选择前 3 个,而且如果有 20 个列表并且我不想选择第 17 个项目,:not 选择器如何实现这一点? (而不是 .classes:nth-last-child(4) )
  • 我相信更简单、更简单的解决方案是将第 17 个元素添加到第一个 CSS 选择器,如下所示:.classes, .classes:nth-child(17) { background: green; } .classes:nth-child(n+4) { background: red; }。但是,如果您尝试将此应用于网格元素,则解决方案可能会有所不同。请让我看看你正在做什么的屏幕截图,我会帮忙的。
猜你喜欢
  • 2014-12-10
  • 1970-01-01
  • 2023-04-05
  • 2020-02-08
  • 2013-05-22
  • 1970-01-01
  • 2016-03-19
  • 2010-09-15
  • 2017-11-20
相关资源
最近更新 更多