CSS - First child without certain class

2020-02-06 21:43发布

问题:

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

回答1:

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


回答2:

This selects all span with a .common-class and without an .ignore class.

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

But, because we want to select only the first one, you can override the siblings that follow with the ~ selector.

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

jsBin demo


If you are already using jQuery, this can also be done with

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


回答3:

No, it is not possible. The selector :first-child:not(.ignore) selects an element that is the first child of its parent and does not belong to class ignore. There is no “first of class” selector and no “first not of class” selector either.

You could use the selector .ignore + :not(.ignore), but it matches any element that is not in class ignore and immediately follows an element in that class. But it matches too much, not just the first one of such elements. Depending on the markup structure, this selector might still be suitable in a particular situation, even though it is not an answer to the general question asked.



回答4:

You don't have to select the div using a class. What about other css solutions like nth-child etc.? Of course, this requires the knowledge of a document structure.