user828591 user828591 - 1 year ago 74
CSS Question

Select the nth following sibling

I wondered if there is a better solution than to what I found without changing the html-structure

The HTML structure looks like this

<div class="wrap">
<div class="divider"></div>
<div class="block"></div>
<div class="block"></div>
<div class="divider"></div>

So there's various DIVs on the same level, what I want to do is to color every fourth block differently, until a divider appears, then it'd have to recount.

I thought something like
would do the trick, but it actually counts the elements based on the parent, not based on the class.

Here's the JSFiddle to try out.
Block #4 and #8 in each row should be differently colored

And this is how I made it sort-of work:

What I did was to look for the 4th sibling of the .divider like this
.divider + .block + .block + .block + .block

It works, however, I'd have to write the same for the 8th, 12th, 16th, .. block, which doesn't make it automatic anymore.

Is there something like
.divider + .block:nth-sibling(4)
.divider + .block:nth-of-class(4)

Maybe one of you got an idea on how to solve this without changing the source code or using javascript.

Answer Source

Such a pseudo-class would not work because you are expecting it to match elements relative to a different compound selector, which is not how simple selectors work. For example, if you wrote a complex selector that only had a single compound selector with that pseudo-class (and no sibling combinators):


Would you expect this to match .block:nth-child(4n), match nothing at all, or be invalid?

It'd be nice to be able to abridge + .block + .block + .block + .block and make it repeat somehow, but unfortunately due to how the selector syntax is designed, it's just not possible.

You'll have to use JavaScript and/or add extra classes to the appropriate elements instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download