CSS - 没有特定类的第一个子元素

16

是否有可能编写CSS规则来选择一个元素的第一个子元素而不需要特定的类?

例如:

<div>
    <span class="common-class ignore"></span>
    <span class="common-class ignore"></span>
    <span class="common-class"></span>
    <span class="common-class"></span>
</div>
在这种情况下,我想选择第一个没有 ignore 类的 span。我尝试过这个方法,但似乎不起作用:
.common-class:first-child:not(.ignore) {
    ...some rules...
}

更新:

如果我给父级div添加名为parent-class的类,那么Jukka建议的选择器的修改版本可以工作,除非第一个具有class ignore出现在没有该类的第一个之后。上述提到的选择器如下:

.parent-class > .common-class.ignore + .common-class:not(.ignore) {
    ...some rules...
}

如果您尝试这种方式,可以查看演示。http://jsbin.com/jozibazi/1/edit - Kheema Pandey
1
在这种特定情况下:.ignore + .common-class {/* style the first */} 可能 可行;但它可能非常脆弱(并且此方法将使得每当一个 .common-class 元素跟随在 .ignore 元素后面时都会被应用相同的样式)。 - David Thomas
4个回答

19

这个问题类似于选择第一个没有类的元素的CSS选择器,不同之处在于第一个没有类的元素没有被考虑。如前所述,:first-child:not(.ignore)代表其父级中第一个没有类为"ignore"的子元素,而不是第一个符合其他选择器的子元素。

你可以使用我在我的答案中描述的兄弟组合技术,将类选择器替换为包含类选择器的:not()伪类:

.common-class:not(.ignore) {
    /* Every span without class .ignore, including the first */
}

.common-class:not(.ignore) ~ .common-class:not(.ignore) {
    /* Revert above declarations for every such element after the first */
}

1
如果你有`.cc|.cc.ignore|.cc|.cc.ignore'...等等,你不能在第一个匹配后停止CSS。它会继续搜索该模式直到DOM(或DOOM)的结尾。 - tao

7

这将选择所有具有 .common-class 类且没有 .ignore 类的 所有 span 元素。

span.common-class:not(.ignore) {
  color: blue;
}

但是,因为我们只想选择第一个,所以可以使用~选择器覆盖其后面的兄弟元素。

span.common-class:not(.ignore) ~ span {
  color: black;   /* or   color: inherit; */
}

jsBin演示


如果您已经在使用jQuery,也可以使用以下代码实现:

$("span.common-class:not(.ignore):first").css('color', 'blue');

6
不可以。选择器:first-child:not(.ignore)选择了一个是其父元素的第一个子元素且不属于类ignore的元素,但没有“第一个类”选择器也没有“第一个非类”选择器。
您可以使用选择器.ignore + :not(.ignore),但它匹配任何不在类ignore中并紧随该类元素之后的元素。但是它匹配了太多内容,不仅限于这些元素的第一个。根据标记结构的不同,这个选择器可能仍然适用于特定情况,尽管它并不是对所提出的一般问题的答案。

我使用了你建议的选择器 .ignore + :not(.ignore),但为了避免太多元素,我向父级 div (parent-class) 添加了一个类,并使用了这个选择器 .parent-class > .ignore + :not(.ignore) - se7entyse7en

0

您不必使用类来选择 div。其他 CSS 解决方案如 nth-child 等呢?当然,这需要了解文档结构。


2
这不是一个答案。如果有必要,应该作为评论发布。 - Jukka K. Korpela
嗯,这取决于实际情况,也许它是固定结构,尽管我承认我曲解了问题。和平与爱。 - ondObno

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接