Alternate table row color using CSS?

2018-12-31 14:07发布

I am using a table with alternate row color with this.

tr.d0 td {
  background-color: #CC9999;
  color: black;
}
tr.d1 td {
  background-color: #9999CC;
  color: black;
}
<table>
  <tr class="d0">
    <td>One</td>
    <td>one</td>
  </tr>
  <tr class="d1">
    <td>Two</td>
    <td>two</td>
  </tr>
</table>

Here I am using class for tr, but I want to use only for table. When I use class for table than this apply on tr alternative.

Can I write my HTML like this using CSS?

<table class="alternate_color">
    <tr><td>One</td><td>one</td></tr>
    <tr><td>Two</td><td>two</td></tr>
    </table>

How can I make the rows have "zebra stripes" using CSS?

9条回答
高级女魔头
2楼-- · 2018-12-31 14:37

can i write my html like this with use css ?

Yes you can but then you will have to use the :nth-child() pseudo selector (which has limited support though):

table.alternate_color tr:nth-child(odd) td{
   /* styles here */
}
table.alternate_color tr:nth-child(even) td{
   /* styles here */
}
查看更多
若你有天会懂
3楼-- · 2018-12-31 14:40
<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>
查看更多
与风俱净
4楼-- · 2018-12-31 14:41

We can use odd and even CSS rules and jQuery method for alternate row colors

Using CSS

table tr:nth-child(odd) td{
           background:#ccc;
}
table tr:nth-child(even) td{
            background:#fff;
}

Using jQuery

$(document).ready(function()
{
  $("table tr:odd").css("background", "#ccc");
  $("table tr:even").css("background", "#fff");
});

table tr:nth-child(odd) td{
           background:#ccc;
}
table tr:nth-child(even) td{
            background:#fff;
}
<table>
  <tr>
    <td>One</td>
    <td>one</td>
   </tr>
  <tr>
    <td>Two</td>
    <td>two</td>
  </tr>
</table>

查看更多
还给你的自由
5楼-- · 2018-12-31 14:44

Most of the above codes won't work with IE version. The solution that works for IE+ other browsers is this.

   <style type="text/css">
      tr:nth-child(2n) {
             background-color: #FFEBCD;
        }
</style>
查看更多
十年一品温如言
6楼-- · 2018-12-31 14:45

Just add the following to your html code (withing the <head>) and you are done.

HTML:

<style>
      tr:nth-of-type(odd) {
      background-color:#ccc;
    }
</style>

Easier and faster than jQuery examples.

查看更多
若你有天会懂
7楼-- · 2018-12-31 14:46

You can use nth-child(odd/even) selectors however not all browsers (ie 6-8, ff v3.0) support these rules hence why most solutions fall back to some form of javascript/jquery solution to add the classes to the rows for these non compliant browsers to get the tiger stripe effect.

查看更多
登录 后发表回答