Creating a checkerboard pattern using CSS selectors

I have a list of div elements that are currently displayed in two columns using CSS floats. I would like to "alternate" the border color of these elements. I used the quoted alternative because I really want the two divs on each "line" to alternate. Below is an example of what I want as the final state:

1blue   2green
3green  4blue
5blue   6green
7green  8blue

      

If I just use nth-child (even) or nth-child (odd), I get the same color in each column vertically, like this:

1blue 2green
3blue 4green
5blue 6green
7blue 8green

      

The divs I want to customize are located inside the WordPress loop, so I don't have much control over the markup (which is why I was hoping to use nth-child CSS). Unfortunately, there is no markup that would allow me to target every single line.

Is there some nth-child template that would allow me to do something like blue[1], green[2],blue[2],etc

for an unlimited number of elements?

I tend to have a very good understanding of CSS, but it hurts my brain a little, so thanks in advance for any help!

+3


source to share


2 answers


You seem to be making a simple checkerboard, so if you set everything to green, you just need to override everything that should be blue. can also take a fomula that gives or is somewhat offset . nth-child

n

n

As you numbered them, note that in the right column you have 4

and 8

(will be 12

), so you need every fourth element, and on the left you have 1

u 5

(next will 9

), so you also need the 4th plus one (1 technically 4*0+1

).

There is a script here that demonstrates 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:

css checkerboard

+11


source


You have to use nth-child like this

div:nth-child(1){…your code here…}
div:nth-child(2){…your code here…}
div:nth-child(3){…your code here…}
div:nth-child(4){…your code here…}
div:nth-child(5){…your code here…}
div:nth-child(6){…your code here…}
div:nth-child(7){…your code here…}
div:nth-child(8){…your code here…}

      



This way you can do anything to each of your 8 divs.

-1


source







All Articles