Kevin Williams
Kevin Williams

Reputation: 196

change the background-color of every other element

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

Answers (3)

Omi
Omi

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.

  • tr:nth-child(2n+1) Represents the odd rows of an HTML table.
  • tr:nth-child(odd) Represents the odd rows of an HTML table.
  • tr:nth-child(2n) Represents the even rows of an HTML table.
  • tr:nth-child(even) Represents the even rows of an HTML table.
  • span:nth-child(0n+1) Represents a span element which is the first child of its parent; this is the same as the :first-child selector.
  • span:nth-child(1) Equivalent to the above.
  • span:nth-child(-n+3) Matches if the element is one of the first three children of its parent and also a span.

.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

jafarbtech
jafarbtech

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

Alireza
Alireza

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

Related Questions