I need to make a ul that changes background colors in groups of 4 li’s (zebra striping but I want to be able to apply the background color once in the css and then access it with JQuery). I don’t want to just use something like nth-child because li’s may need to be removed periodically, and I want the layout to remain without having to go in and change the class for each li. I’m not sure if this makes sense, but I’ve put together an example html to try to show what I’m talking about.
I’d appreciate any possible suggestions for how to change the style (from white to grey background) at every fourth element (li).
Here are the styles:
li.grey {
background-color: #b9b9b9;
}
li.white {
background-color: #ffffff;
}
.items_layout {
padding: 0 0 0 0;
width: 580px;
}
.item_container {
color: #212D31;
overflow: hidden;
width: 580px;
}
.item_container li {
float: left;
width: 131px;
height: 130px;
padding: 2px; 5px 5px 5px;
border-style:solid;
border-width:2px;
border-color: red;
list-style: none;
}
.sample_header {
font-weight: bold;
padding: 2px 0 1px 0;
color: #0071B5;
}
And here’s the html:
<div class="items_layout">
<ul class="item_container">
<li><p class="sample_header">Header</p>
White background<br />(background-color: #ffffff)</li>
<li><p class="sample_header">Header</p>
White background<br />(background-color: #ffffff)</li>
<li><p class="sample_header">Header</p>
White background<br />(background-color: #ffffff)</li>
<li><p class="sample_header">Header</p>
White background<br />(background-color: #ffffff)</li>
<li><p class="sample_header">Header</p>
Grey background<br />(background-color: #b9b9b9;)<br />starts here</li>
<li><p class="sample_header">Header</p>
Grey background<br />Should go here</li>
<li><p class="sample_header">Header</p>
Grey background<br />Should go here</li>
<li><p class="sample_header">Header</p>
Grey background<br />Should go here</li>
<li><p class="sample_header">Header</p>
Back to<br /> white background here</li>
<li><p class="sample_header">Header</p>
Back to<br /> white background here</li>
</ul>
</div>
I appreciate any help or thoughts on this.
Thanks!
A simple iterate over all li elements and set the background seems to be the easier. You may need to call this method whenever you add/remove elements from the list.
DEMO here.
JS Function: