Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate background colors for list items

Tags:

html

css

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> 
like image 565
Brad Avatar asked Dec 11 '08 03:12

Brad


People also ask

How do I change the background color of a list in HTML?

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.

Which color property is used to change the background?

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.

What are background colors?

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.


2 Answers

How about some lovely CSS3?

li { background: green; } li:nth-child(odd) { background: red; } 
like image 63
Adam C Avatar answered Oct 03 '22 04:10

Adam C


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'); }); 
like image 34
Phil.Wheeler Avatar answered Oct 03 '22 04:10

Phil.Wheeler