0

i want to have different background color on same repeating div. example:

<div class="test"></div> <!-- this div bg color will be blue -->
<div class="test"></div> <!-- this div bg color will be red-->
<div class="test"></div> <!-- this bg div color will be blue -->
<div class="test"></div> <!-- this bg div  color will be red-->
<div class="test"></div> <!-- this bg div color will be blue -->
<div class="test"></div> <!-- this bg div  color will be red-->
<div class="test"></div> <!-- this bg div color will be blue -->
<div class="test"></div> <!-- this bg div  color will be red-->
<div class="test"></div> <!-- this bg div color will be blue -->
<div class="test"></div> <!-- this bg div  color will be red-->
<!-- and more and more, you got the idea... -->

I know that i could print in server side different class for each, but i'm looking for a way to do this in CSS on the same class if its possible, without adding classes/ids/Js. Thank you.

BenB
  • 2,747
  • 3
  • 29
  • 54

4 Answers4

3

This solves your problem:

.test:nth-child(odd) {
    background: blue;
}
.test:nth-child(even) {
    background: red;
}

fiddle

qtgye
  • 3,580
  • 2
  • 15
  • 30
1

You can use :nth-child(n) selector.

div.test:nth-child(odd) {
    background-color: blue;
}

div.test:nth-child(even) {
    background-color: red;    
}

Check out the example here http://www.w3schools.com/cssref/sel_nth-child.asp

Note that IE6, 7, 8 do not support this selector.

bestalign
  • 227
  • 1
  • 9
1

You can use the nth-child(even|odd) selector:

.test:nth-child(even) {background: blue}
.test:nth-child(odd) {background: red}

You can see more examples at http://www.w3.org/Style/Examples/007/evenodd.en.html

Jason Watmore
  • 4,521
  • 2
  • 32
  • 36
1

If your concern for not adding a second css class is the size of the HTML, or even for the simplicity, you don't have to use the 'test' class either, as long as you can find a container element wrapping those.

Check this fiddle: http://jsfiddle.net/BuddhiP/aq3uz/

<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>

And the CSS is

.container div {
height: 1em;    
}


 .container div:nth-child(odd) {
    background: blue;
   }
   .container div:nth-child(even) {
    background: red;
   }
BuddhiP
  • 6,231
  • 5
  • 36
  • 56