Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make every other div a different color

I'm stuck with some code which I would like the bg color to be alternated to a color on .itemrow of #F8F8F8

Here's the paste bin: http://pastebin.com/mgHYzJAd

.itemrow {
    padding-top:20px;
    padding-bottom:20px;
    background-color:#f8f8f8;
}

and the project page if you wanted to see it: http://paolor.co.uk/projects/grubrun/menu.php

I've tried to do some research and nth-child(odd) has come up a few times but it's not something I've ever come across before in the 3 months I've been doing front end.

Any help is appreciated and thank you in advance! :o) Paolo

like image 613
Paolo Resteghini Avatar asked Dec 05 '22 02:12

Paolo Resteghini


2 Answers

What about:

.itemrow:nth-child(even) {
    background-color:#f8f8f8;
}

Instead of even you could use odd too. It's a surprise to me that you haven't found it before. It's been around quite a while and is supported at least since IE9, and I think even from IE7. Then again, you don't need it that often. I think alternating backgrounds are the only purpose I've seen it used for so far.

like image 95
GolezTrol Avatar answered Dec 06 '22 16:12

GolezTrol


For more flexibility, use a multiplier:

.itemrow:nth-child(2n) {
    background-color:#f8f8f8;
}

which can allow you to do this:

.itemrow:nth-child(2n + 1) {
    background-color:#f8f8f8;
}

Fiddle: http://jsfiddle.net/k37m1yak/ Browser Support: http://caniuse.com/#search=nth-child

like image 33
Phillip Chan Avatar answered Dec 06 '22 15:12

Phillip Chan