DEV Community

Cover image for CSS: select first-of-class with the subsequent sibling combinator

CSS: select first-of-class with the subsequent sibling combinator

Phil Nash on March 18, 2018

There are a whole bunch of CSS selectors available to web developers, but sometimes there's still not enough. I found this recently when building t...
Collapse
 
equinusocio profile image
Mattia Astorino • Edited

Hi, after some test, i found an alternative solution (i think)

codepen.io/equinusocio/pen/NYpegd

<div class="cont">
    <div class="box">box</div>
    <div class="box">box</div>
    <div class="box box--special">box</div>
    <div class="box box--special">box</div>
    <div class="box box--special">box</div>
    <div class="box box--special">box</div>
    <div class="box box--special">box</div>
    <div class="box box--special">box</div>
</div>
.box {
    width: 100px;
    height: 100px;
    padding: 8px;
    background-color: yellowgreen;
    margin: 10px;
}

.box--special {
    border: 1px solid #000;
    background-color: #fff;
}

.box--special + .box--special:not(:last-child) {
    background-color: red;
    color: #FFF;
}

Collapse
 
philnash profile image
Phil Nash

That doesn’t do the same, notably the + combinator is the direct sibling, so if you throw another <div> in the middle with a different class it breaks.

Collapse
 
equinusocio profile image
Mattia Astorino • Edited

Yes i know. But both solutions have caveats since even with the subsequent sibling the code will break if you use another element type (because you are bound to type of the element).

BTW, nice exploration, thank you :)

Collapse
 
equinusocio profile image
Mattia Astorino • Edited

Nice! We now have to wait the full support.

Collapse
 
philnash profile image
Phil Nash

Well, full support for the latest :nth-child(). You can definitely use the subsequent sibling selector for now.

Collapse
 
equinusocio profile image
Mattia Astorino

I mean lv 4 selector :)

Thread Thread
 
philnash profile image
Phil Nash

I can’t wait either!

Collapse
 
chrismitchell profile image
Chris Mitchell

Great post Phil! This would have been perfect timing if released last week but none the less an great piece.

Collapse
 
philnash profile image
Phil Nash

Replied to you on Twitter too, but wanted to re-iterate. I wish I written this a week (or more) ago too. It's been in my drafts for ages.

Glad you did sort it out yourself though!