Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate div background color

I have a structure like the following:

<div class="wrapper"...>
   <a href="#"...>blah</a>
   <div class="post"...>stuff</div>
</div>

And it repeats throughout a dynamic page a few times. I would like to alternate the background colors of the div class "post" with two colors, but CSS's nth-child pseudo class only seems to work with items that are directly sequential.

Is there a way (CSS, Javascript, jQuery, etc.) that I can alternate the div background colors?

like image 596
redgem Avatar asked May 30 '11 18:05

redgem


People also ask

Can div have color?

With Hexadecimal values, you can set a background color for a div or any other element with a total of 6 characters. Hex colors start with the hash sign (#), any number from 0 to 9, and finally any letter from A to F.


2 Answers

jQuery's :odd and :even selectors are pretty handy:

$(".post:even").css("background-color","blue"); 
$(".post:odd").css("background-color","red"); 

HTML:

<div class="wrapper">
   <a href="#">blah</a>
   <div class="post">stuff</div>
</div>
<div class="wrapper">
   <a href="#">blah</a>
   <div class="post">stuff</div>
</div>
...

http://jsfiddle.net/thomas4g/uaYd9/2/

EDIT:

The non-jQuery, quick JS way:

var posts = document.getElementsByClassName("post");
for(var i=0;i<posts.length;i++) {
  posts[i].classList.add(i % 2 === 0 ? "even" : "odd");
  //or
  posts[i].style["background-color"] = i % 2 === 0 ? "blue" : "red";
}
like image 62
Thomas Shields Avatar answered Sep 18 '22 09:09

Thomas Shields


the jquery way:

$('.post:even').css('background-color','green');
$('.post:odd').css('background-color','red');
like image 32
gion_13 Avatar answered Sep 21 '22 09:09

gion_13