table 行交替背景颜色的最佳实践

Best practice for alternating background colors on table rows

我正在设计多个 table 的样式,其中包含一行数据。每行在 table 的宽度上都应该是可读的,因此我将在交替的行中添加浅色背景色。

是否有 "best practice" 来决定 table 的第一行是 white 还是 color 背景?

最好的选择是 :nth-child css 选择器!

至于颜色,以浅灰色作为背景不会出错。与本网站对代码片段所做的类似。

将 class 应用到您的 table 并像这样使用它..

.table {
  border-collapse: collapse;
}
.table th, .table tr, .table td {
  border: 1px solid black;
}
.table tr:nth-child(odd) {
  background: #f2f2f2;
}
.table td {
  padding: 3px;
}
<table class="table">    
    <tr>
        <td>Something</td>
        <td>Cool</td>
        <td>Here</td>
    </tr>
    <tr>
        <td>Something</td>
        <td>Cool</td>
        <td>Here</td>
    </tr>    
    <tr>
        <td>Something</td>
        <td>Cool</td>
        <td>Here</td>
    </tr>
</table>

编辑

编辑了我的代码片段以更好地反映问题。

使用nth-child(偶数)或nth-child(奇数),看看我的codepen

示例

td:nth-child(even) {
  background:#d7d7d7;
}

就最佳实践而言,第一行应与 table header 颜色形成对比。就代码而言:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script TYPE="text/javascript">
$(document).ready(function() {
 zebraRows('tbody tr:odd td', 'odd');
});
 
//used to apply alternating row styles
function zebraRows(selector, className)
{
  $(selector).removeClass(className).addClass(className);
}
  
// Tweak as required
$(function(){
 $("table").css("width", "80%");
 $("th").css("text-align", "left");
 $(".index").css("width", "50px");
 $(".u_date").css("width", "150px");
});
</script>