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...
}
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 classignore
. 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 classignore
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.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: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.
This selects all span with a
.common-class
and without an.ignore
class.But, because we want to select only the first one, you can override the siblings that follow with the
~
selector.jsBin demo
If you are already using jQuery, this can also be done with