Alternate background colors for list items

前端 未结 9 1829
一向
一向 2020-12-04 07:42

I have a list, and each item is linked, is there a way I can alternate the background colors for each item?

相关标签:
9条回答
  • 2020-12-04 08:31

    How about some lovely CSS3?

    li { background: green; }
    li:nth-child(odd) { background: red; }
    
    0 讨论(0)
  • 2020-12-04 08:34

    Try adding a pair of class attributes, say 'even' and 'odd', to alternating list elements, e.g.

    <ul>
        <li class="even"><a href="link">Link 1</a></li>
        <li class="odd"><a href="link">Link 2</a></li>
        <li class="even"><a href="link">Link 3</a></li>
        <li class="odd"><a href="link">Link 4</a></li>
        <li class="even"><a href="link">Link 5</a></li>
    </ul>
    

    In a <style> section of the HTML page, or in a linked stylesheet, you would define those same classes, specifying your desired background colours:

    li.even { background-color: red; }
    li.odd { background-color: blue; }
    

    You might want to use a template library as your needs evolve to provide you with greater flexibility and to cut down on the typing. Why type all those list elements by hand?

    0 讨论(0)
  • 2020-12-04 08:35

    You can achieve this by adding alternating style classes to each list item

    <ul>
        <li class="odd"><a href="link">Link 1</a></li>
        <li><a href="link">Link 2</a></li>
        <li class="odd"><a href="link">Link 2</a></li>
        <li><a href="link">Link 2</a></li>
    </ul>
    

    And then styling it like

    li { backgorund:white; }
    li.odd { background:silver; }
    

    You can further automate this process with javascript (jQuery example below)

    $(document).ready(function() {
      $('table tbody tr:odd').addClass('odd');
    });
    
    0 讨论(0)
提交回复
热议问题