在CSS初级项目里,表格是最常见的展示数据的元素。如果所有行都是同一种白色背景,看久了容易串行。我们可以通过nth-child选择器给表格的奇偶行设置不同背景色,再用border颜色做收边,整体就显得清爽许多。

一、准备基础表格结构
先写一个简单的HTML表格,后面所有样式都基于它来写。
<table class="demo-table">
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>苹果</td>
<td>5元</td>
</tr>
<tr>
<td>2</td>
<td>香蕉</td>
<td>3元</td>
</tr>
<tr>
<td>3</td>
<td>橘子</td>
<td>4元</td>
</tr>
</tbody>
</table>
二、用nth-child实现交替行背景
CSS里的nth-child(odd)选中奇数位置子元素,nth-child(even)选中偶数位置子元素。我们在tbody里的tr上使用它们。
/* 表格基础边框 */
.demo-table {
width: 100%;
border-collapse: collapse;
font-family: sans-serif;
}
/* 表头样式 */
.demo-table th {
background: #f0f0f0;
padding: 8px;
border: 1px solid #cccccc;
}
/* 奇数行背景 */
.demo-table tbody tr:nth-child(odd) {
background-color: #fafafa;
}
/* 偶数行背景 */
.demo-table tbody tr:nth-child(even) {
background-color: #ffffff;
}
三、用border颜色组合美化
交替背景加上合适的border颜色,能让表格不显生硬。我们给单元格统一细边框,并选用浅灰颜色减少割裂感。
.demo-table td {
padding: 8px;
border: 1px solid #e0e0e0;
}
/* 鼠标悬停时加深背景,提升交互感 */
.demo-table tbody tr:hover {
background-color: #f5f9ff;
}
常见border颜色搭配建议
| 场景 | border颜色 | 效果 |
|---|---|---|
| 浅色背景表格 | #e0e0e0 | 细腻不抢眼 |
| 深色背景表格 | #444444 | 对比清晰 |
| 强调分隔 | #cccccc | 中等存在感 |
四、完整示例组合
把前面的规则合并,就是一个可直接用的初级表格美化方案。
.demo-table {
width: 100%;
border-collapse: collapse;
font-family: sans-serif;
}
.demo-table th {
background: #f0f0f0;
padding: 8px;
border: 1px solid #cccccc;
}
.demo-table td {
padding: 8px;
border: 1px solid #e0e0e0;
}
.demo-table tbody tr:nth-child(odd) {
background-color: #fafafa;
}
.demo-table tbody tr:nth-child(even) {
background-color: #ffffff;
}
.demo-table tbody tr:hover {
background-color: #f5f9ff;
}
五、小结
使用nth-child控制奇偶行背景,再用低对比度的border颜色收边,是CSS初级项目里性价比很高的表格美化做法。不需要任何脚本,纯样式就能让页面更工整。熟练后还可以把背景色换成品牌色,进一步统一站点风格。