Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS odd even with 2 cols

My html is like this:

<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>

and there are 2 articles in one line with float and i want them to change the color like:

blue green
green blue
blue green
green blue

how can i do that with css?

like image 941
Andreas Avatar asked Mar 06 '14 13:03

Andreas


1 Answers

There are four articles in a pattern, so some offset of 4n ought to do the trick. This seems to work (Fiddle):

article {color:blue}
article:nth-child(4n-1), article:nth-child(4n-2) {color:green}

If you don't like minus, plus also works just the same (Fiddle):

article {color:blue}
article:nth-child(4n+2), article:nth-child(4n+3) {color:green}

Just to explain the entire logic, it's a matter of shifting the 4n pattern:

                   4n-3    4n-2    4n-1
#   COLOR   4n     4n+1    4n+2    4n+3
-- ------  -----  ------  ------  ------
 1  blue    -       0        -        -
 2  green   -       -        0        -
 3  green   -       -        -        0
 4  blue    1       -        -        -
 5  blue    -       1        -        -
 6  green   -       -        1        -
 7  green   -       -        -        1
 8  blue    2       -        -        -
 9  blue    -       2        -        -
10  green   -       -        2        -
11  green   -       -        -        2
12  blue    3       -        -        -
13  blue    -       3        -        -

-1 and +3 are congruent mod 4, as are -2 and +2, so these refer to the same elements (although the value of n is technically different for each).

You could even swap it around and color 4n and 4n+1 blue (Fiddle):

article {color:green}
article:nth-child(4n), article:nth-child(4n+1) {color:blue}
like image 70
lc. Avatar answered Nov 12 '22 07:11

lc.