Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternating colours per row per div using only css

I want to know if this is possible using only CSS:

Black White
White Black
Black White
White Black

The name represents the colour background I want. In this jsfiddle, I've hardcoded it to show exactly what it is that I want, but the amount of divs will be dynamic, so I don't know how many there will be.

How do I achieve this?

like image 737
Bird87 ZA Avatar asked Apr 21 '15 10:04

Bird87 ZA


1 Answers

You'll need to use the :nth-child pseudo class here.


OPTION 1

This first option requires the use of 2 selectors

The first handles the styling of the divs in the left column of the grid. Numbering those ones gives us 1,5,9,13,... which you can express as 4n-3 (4*1-3=1, 4*2-3=5, 4*3-3=9, 4*4-3=13, ...). This can also be expressed as 4n+1, if you prefer.

The second selector, to handle the styling of the divs in the right column, is more straightforward as that is simply every fourth div, which can be expressed as 4n (4*1=4, 4*2=8, 4*3=12, 4*4=16, ...).

div{
  background:#fff;
  display:inline-block;
  height:100px;
  width:50%;
}
div:nth-child(4n-3),div:nth-child(4n){
  background:#000;
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

OPTION 2

This second option achieves the same result with a single selector using the negation pseudo class :not().

The inverse selection to that in option one can be expressed using 4n-1 and 4n-2 (or 4n+3 and 4n+2) so we'll select all the divs, excluding those that match these expressions.

div{
    background:#fff;
    display:inline-block;
    height:100px;
    width:50%;
}
div:not(:nth-child(4n-1)):not(:nth-child(4n-2)){
    background:#000;
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

FURHTER READING ON MDN

  • Overview of CSS pseudo classes
  • More information on the :nth-child pseudo class
  • More information on the negation pseudo class

ASIDE

I tried my best to come up with a single CSS expression to suit this but couldn't. If anyone has any success doing so, please let me know. The sequence we're looking to match is: 1,4,5,8,9,12,13,16,17,20,...,2n-(n%2)

like image 198
Shaggy Avatar answered Sep 30 '22 06:09

Shaggy