Danka
Danka

Reputation: 291

How to alternate style (background color ) for div inside div

How to alternate style (background color with jquery) for div inside div with id="container" alternately ( even and odd ) if I have HTML like this

<div id="container">
   <div></div> 
   <div></div>
   <div></div>
   <div></div>
...
</div>

I know with table like

#tbl_users tr:nth-child(even) {background: #CCC;}
#tbl_users tr:nth-child(odd) {background: #FFF;}

but how to div apply something like this ?

Upvotes: 4

Views: 8562

Answers (5)

gaurang171
gaurang171

Reputation: 9080

<div id="container">
   <div>A</div> 
   <div>B</div>
   <div>C</div>
   <div>D</div>
</div>

div#container div:nth-child(even) {background: #FF00CC;}
div#container div:nth-child(odd) {background: #CC00FF;}

Please try this link http://codebins.com/codes/home/4ldqpbz

Upvotes: 0

Andrej
Andrej

Reputation: 606

Did you try:

div#container div:nth-child(even) {background: #CCC;}
div#container div:nth-child(odd) {background: #FFF;}

nth-child should work regardless of the tag.

Upvotes: 6

pistacchio
pistacchio

Reputation: 58883

$('#container>div:odd').css("background-color", "#ff0000");
$('#container>div:even').css("background-color", "#00ff00");

Upvotes: 4

yoavmatchulsky
yoavmatchulsky

Reputation: 2960

using the same trick:

#container div:nth-child(even) {background: #CCC;}
#container div:nth-child(odd) {background: #FFF;}

Upvotes: 0

Niklas
Niklas

Reputation: 30002

It works exactly the same way with divs. With the above structure, you could get the same effect with:

#container div:nth-child(even) {background: #CCC;}
#container div:nth-child(odd) {background: #FFF;}

Upvotes: 2

Related Questions