Consider this HTML structure with items arranged at the same level:
<div class="h2">Title: Colors</div>
<div class="pair">Hello world (1)</div>
<div class="pair">Hello world (2)</div>
<div class="pair">Hello world (3)</div>
<div class="pair">Hello world (4)</div>
<div class="pair">Hello world (5)</div>
<div class="pair">Hello world (6)</div>
<div class="h2">Title: Units</div>
<div class="pair">Hello world (1)</div>
<div class="pair">Hello world (2)</div>
<div class="pair">Hello world (3)</div>
<div class="pair">Hello world (4)</div>
<div class="pair">Hello world (5)</div>
<div class="pair">Hello world (6)</div>
How can I target and style the n+3 and n+4 .pair elements following the previous .h2 element?
This means 1&2 are white, 3&4 are pink, 5&6 are white, and so on.
I attempted to use
.pair:nth-child(4n+3), .pair:nth-child(4n+4) { background: #FFAAAA; }
, but it includes the children of the body where the h2
elements also exist, disrupting the desired styling balance.
Edit: No pure CSS selector exists to efficiently select adjacent items in a pattern like .class (n+3). As an alternative, a series of CSS selectors using
div + .class + .class + .class ...
; combined with :nth-child(n+3)
or :nth-of-type(n+3)
; or utilizing JS is necessary. Do you know any other workaround? Your input is appreciated!