Variable colors in a string on a 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 is the colored background that I want. In this jsfiddle, I hard-coded it to show what exactly I want, but the number of divs will be dynamic, so I don’t know how much will be.

How do I achieve this?

+7
css css-selectors css3
source share
1 answer

You will need :nth-child pseudo class here.


OPTION 1

This first parameter requires 2 selectors

The first controls the style of divs in the left column of the grid. The numbering of these numbers 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, ...). It can also be expressed as 4n+1 if you prefer.

The second selector for processing section styles in the right column is simpler, because it is just 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 a negative pseudo-class :not() .

The reverse choice is that in the option one can be expressed using 4n-1 and 4n-2 (or 4n+3 and 4n+2 ), so we will select all divs except those that correspond to 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> 

EXTREME READING ON MDN


ASIDE

I tried my best to come up with one CSS expression for this, but couldn't. If anyone has success, let me know. The sequence that we want to match: 1,4,5,8,9,12,13,16,17,20,...,2n-(n%2)

+15
source share

All Articles