How to alternate style (background color ) for div

2019-05-03 17:01发布

问题:

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 ?

回答1:

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.



回答2:

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


回答3:

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;}


回答4:

using the same trick:

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


回答5:

<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