I have a list of divs
that appear 4 in a row with a class and I would like to create a checkerboard background style, meaning:
You may also use only 4 selectors to switch the background-color. (answer similar to @MichałMiszczyszyn => shorter approach)
The repeating pattern goes on 2 rows of 4 elements, the choice of :nth-child(8n)
is indeed the basic pattern to work on, example :
:nth-child(8n-1),
:nth-child(8n-3),
:nth-child(8n-6),
:nth-child(8n-12){
background:/* switch to the other value here */;
}
.square {
width:25%;
margin:auto;
background:turquoise;
counter-reset:div;
overflow:hidden; /* to deal with float */
}
.square div {
float:left;
width:25%;
text-align:center;
background:green;
}
.square div:nth-child(8n-1),
.square div:nth-child(8n-3),
.square div:nth-child(8n-6),
.square div:nth-child(8n-12){
background:tomato;
}
/* demo purpose */
body:hover div div {
background:initial;/* resets to none to show parents background */
}
.square div:before {
content:'';
padding-top:100%;
display:inline-block;
vertical-align:middle;
}
.square div:after {
counter-increment:div;
content:counter(div);
display:inline-block;
vertical-align:middle;
font-size:2vw;
}
The pattern will repeat itself every 8 elements.
Notice that you can spare the initial background-color
of squares and use the parent background.