表格美化
斑马纹、悬停高亮、响应式表格、colgroup 列组
表格美化
纯默认表格很丑——几行 CSS 能显著提升可读性和美观度。
学完本章你将: 掌握斑马纹、悬停高亮、响应式表格、colgroup 列组。
斑马纹
html
<style>
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px; border-bottom: 1px solid #ddd; }
th { background-color: #4CAF50; color: white; }
/* 偶数行灰色 */
tr:nth-child(even) { background-color: #f2f2f2; }
</style>
悬停高亮
html
<style>
/* 鼠标悬停整行变色 */
tr:hover { background-color: #ddd; }
</style>
响应式表格
html
<style>
/* 小屏幕时表格可以横向滚动 */
.table-container {
overflow-x: auto; /* 超出时出现滚动条 */
}
</style>
<div class="table-container">
<table>
<!-- 内容较多的表格 -->
</table>
</div>
colgroup 列组样式
html
<table>
<colgroup>
<col span="2" style="background-color: #f9f9f9;">
<col style="background-color: #e8f4f8;">
</colgroup>
<tr>
<th>姓名</th> <!-- 浅灰 -->
<th>年龄</th> <!-- 浅灰 -->
<th>邮箱</th> <!-- 浅蓝 -->
</tr>
</table>