CSS - 没有特定班级的第一个孩子

2022-01-10 00:00:00 css-selectors css

是否可以编写 CSS 规则来选择没有特定类的元素的第一个子元素?

示例:

<span class="普通类忽略"></span><span class="普通类忽略"></span><span class="common-class"></span><span class="common-class"></span></div>

在这种情况下,我想选择没有类 ignore 的第一个 span.我试过了,但似乎没有用:

.common-class:first-child:not(.ignore) {...一些规则...}

更新:

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

.parent-class >.common-class.ignore + .common-class:not(.ignore) {...一些规则...}

解决方案

这个问题类似于第一个元素的 CSS 选择器有类,除了第一个元素没有一个类.如前所述,:first-child:not(.ignore) 表示一个元素,它是其父元素的第一个子元素,并且没有类ignore",而不是第一个匹配其余元素的子元素选择器.

您可以将覆盖技术与我在 我对链接问题的回答,将类选择器替换为包含类选择器的 :not() 伪类:

.common-class:not(.ignore) {/* 每个没有 class .ignore 的 span,包括第一个 */}.common-class:not(.ignore) ~ .common-class:not(.ignore) {/* 在第一个元素之后为每个这样的元素恢复上述声明 */}

Is it possible to write a CSS rule to select the first child of an element without a specific class?

example:

<div>
    <span class="common-class ignore"></span>
    <span class="common-class ignore"></span>
    <span class="common-class"></span>
    <span class="common-class"></span>
</div>

In this case I would like to select the first span without class ignore. I tried this, but didn't seem to work:

.common-class:first-child:not(.ignore) {
    ...some rules...
}

UPDATE:

If I add a class to the parent div named parent-class, a modified version of the selector suggested by Jukka works except when the first span with class ignore comes after the first one without. The above-mentioned selector is the following:

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

解决方案

This question is similar to CSS selector for first element with class, except for the first element without a class. As mentioned, :first-child:not(.ignore) represents an element that is the first child of its parent and does not have the class "ignore", not the first child matching the rest of the selector.

You can use the overriding technique with a sibling combinator that I've described in my answer to the linked question, replacing the class selector with the :not() pseudo-class containing a class selector:

.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 */
}

相关文章