I have a list, and each item is linked, is there a way I can alternate the background colors for each item?
<ul> <li><a href="link">Link 1</a></li> <li><a href="link">Link 2</a></li> <li><a href="link">Link 3</a></li> <li><a href="link">Link 4</a></li> <li><a href="link">Link 5</a></li> </ul>
To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.
The background-color property sets the background color of an element. The background of an element is the total size of the element, including padding and border (but not the margin). Tip: Use a background color and a text color that makes the text easy to read.
The background color is, in most cases, displayed in the form of an RGB triplet or a hexadecimal code. The three separate pairs of numbers you are given represent the different color values of the RGB spectrum. The first value stands for the red color, the second for the green color and the last for the blue color.
How about some lovely CSS3?
li { background: green; } li:nth-child(odd) { background: red; }
If you want to do this purely in CSS then you'd have a class that you'd assign to each alternate list item. E.g.
<ul> <li class="alternate"><a href="link">Link 1</a></li> <li><a href="link">Link 2</a></li> <li class="alternate"><a href="link">Link 3</a></li> <li><a href="link">Link 4</a></li> <li class="alternate"><a href="link">Link 5</a></li> </ul>
If your list is dynamically generated, this task would be much easier.
If you don't want to have to manually update this content each time, you could use the jQuery library and apply a style alternately to each <li>
item in your list:
<ul id="myList"> <li><a href="link">Link 1</a></li> <li><a href="link">Link 2</a></li> <li><a href="link">Link 3</a></li> <li><a href="link">Link 4</a></li> <li><a href="link">Link 5</a></li> </ul>
And your jQuery code:
$(document).ready(function(){ $('#myList li:nth-child(odd)').addClass('alternate'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With