I have a list of div elements that I'm currently displaying in two columns using CSS float. I would like to "alternate" the border color of these elements. I used alternate in quotes because what I really want is for the two divs in each "row" to alternate. Below is an example of what I want as my end state:
1blue 2green
3green 4blue
5blue 6green
7green 8blue
If I simply use nth-child(even) or nth-child(odd) I get the same color in each column vertically like:
1blue 2green
3blue 4green
5blue 6green
7blue 8green
The divs I want to target are located inside a WordPress loop so I don't have a lot of control over the markup (which is why I was hoping to use CSS nth-child). Unfortunately there isn't any markup that would allow me to target each individual "row".
Is there any kind of nth-child pattern that would allow me to do something like blue[1], green[2],blue[2],etc for an indefinite number of items?
I normally have a very good understanding of CSS but this is hurting my brain a little so thanks in advance for any help!
It seems like you are making a simple checkerboard, so if you set every thing to green, you just need to override everything that needs to be blue. nth-child can also accept a fomula that gives an n or multiple of n with an offset.
As you have them numbered, note that in the right column you have 4 and 8 (next would be 12), so you need every 4th element, and in the left you have 1 and 5 (next would be 9), so you also need the 4th plus one (1 is technically 4*0+1).
There is a fiddle here that demos it, but the relevant code is:
/* Color everything green */
.checkerboard div {
width:45%;
display:inline-block;
background-color:green;
}
/* Then color the appropriate divs blue */
.checkerboard div:nth-child(4n+1),
.checkerboard div:nth-child(4n) {
background-color:blue;
}
And gives:

I made a CSS checkerboard generator: https://codepen.io/RilDev/pen/mdXegEL

For a 4 by 4 checkerboard it would generate this code:
<div class="board">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<style>
.board {
display: grid;
grid-template-columns: repeat(4, 64px);
}
.square {
width: 64px;
height: 64px;
background: black;
}
.square:nth-child(8n + 1),
.square:nth-child(8n + 3),
.square:nth-child(8n + 6),
.square:nth-child(8n + 8) {
background: white;
}
</style>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With