Reputation: 196
I want to change the background-color of every other element in the following:
<div class="dets">
<div>Simple Layout</div>
<div>Few Pictures/Links</div>
<div>Element Uniformity</div>
</div>
So the first [Simple Layout] would be white, the second [Few Pictures/Links] would be black, and so on. I have three of these structures nested in some other div elements. I know about the :even,:odd methods, but it doesn't do as expected. It continues through each of the "dets" classes, increasing the index each time. I want odd rows white, even rows black. Is there a way to restart the natural index for each "dets" class? I do not want to use a table.
I am currently using the following jQuery to set the background-color:
$(".dets div:odd").css('background-color', 'white');
$(".dets div:even").css('background-color', 'black');
Upvotes: 2
Views: 11963
Reputation: 4007
It is better to use css nth-child.
You can use id instead of class .dets
to decrease the index time like #dets
You can have other selector also you can use that as per your requirement: e.g.
.dets>div:nth-child(even){
background:#000;
color:#fff;
}
.dets>div:nth-child(odd){
background:#fff;
}
<div class="dets">
<div>Simple Layout</div>
<div>Few Pictures/Links</div>
<div>Element Uniformity</div>
</div>
Upvotes: 3
Reputation: 7015
You could achieve this in css itself by using
.dets div:nth-child(odd){ background-color:white; } .dets div:nth-child(even){ background-color:black; }
Upvotes: 2
Reputation: 2449
Try:
$(".dets>div:nth-child(odd)").css('background-color', 'white');
$(".dets>div:nth-child(even)").css('background-color', 'black');
also you can do it only with css:
.dets>div:nth-child(odd){
background-color:white;
}
.dets>div:nth-child(even){
background-color:black;
}
Upvotes: 6