Matthew Matthew - 5 months ago 15
CSS Question

CSS: Targeting :nth-child consistant across 2 parent elements?

Let's say we have a setup like this:

<div class="row"><!-- The .col's in this row are dynamically generated -->
<div class="col 1"></div>
<div class="col 2"></div>
<div class="col 3"></div>
<div class="col 4"></div>
<div class="col 5"></div>
</div>
<div class="row">
<div class="col 1"></div>
<div class="col 2"></div>
<div class="col 3"></div>
<div class="col 4"></div>
</div>

<style>
.col:nth-child(2n+1) {
background: red;
}

/* Style the div's for testing */
div.row {
width: 100%;
border: 1px solid blue;
}
div.col {
padding: 12px 0;
width: 100%;
}
</style>


Here's a working Fiddle: https://jsfiddle.net/1L4rodh4/

Now... the
Nth selector
is working as it should. The problem is that I want to get the elements styled consistently. so that it appears to be seamless between the 2
.row
's. The
.col
's in the first
.row
are dynamically generated and could end up being
even
or
odd
.

Please ask me for clarification if I wasn't clear. I couldn't find any information about this elsewhere. This is something that seems so simple, yet it seems to be impossible.

Is there a better way of doing this, or am I stuck?




I understand I could use JS to get the number of "col"'s in the first "row" and change the selector in the second row. That just seems way too hack-ish for this though.

Answer

You can do that with CSS. See this or this.

.col:first-child:nth-last-child(even) ~ .col:nth-child(2n + 1),
.col:first-child:nth-last-child(even){
  background-color: red;
}

.col:first-child:nth-last-child(odd) ~ .col:nth-child(2n + 2){
  background-color: red;
}

This checks if the number of children are even or odd and styles them appropriately.

Comments