Alternate background colors for list items

前端 未结 9 1828
一向
一向 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:18

    Since you using standard HTML you will need to define separate class for and manual set the rows to the classes.

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

    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');
    });
    
    0 讨论(0)
  • 2020-12-04 08:21

    You can do it by specifying alternating class names on the rows. I prefer using row0 and row1, which means you can easily add them in, if the list is being built programmatically:

    for ($i = 0; $i < 10; ++$i) {
        echo '<tr class="row' . ($i % 2) . '">...</tr>';
    }
    

    Another way would be to use javascript. jQuery is being used in this example:

    $('table tr:odd').addClass('row1');
    

    Edit: I don't know why I gave examples using table rows... replace tr with li and table with ul and it applies to your example

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

    You can by hardcoding the sequence, like so:

    li, li + li + li, li + li + li + li + li {
      background-color: black;
    }
    
    li + li, li + li + li + li {
      background-color: white;
    }
    
    0 讨论(0)
  • 2020-12-04 08:25

    If you use the jQuery solution it will work on IE8:

    jQuery

    $(document).ready(function(){
    $('#myList li:nth-child(odd)').addClass('alternate');
    });
    

    CSS

    .alternate {
    background: black;
    }
    

    If you use the CSS soloution it won't work on IE8:

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

    This is set background color on even and odd li:

      li:nth-child(odd) { background: #ffffff; }
      li:nth-child(even) { background: #80808030; }
    
    0 讨论(0)
提交回复
热议问题