⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

CSS 表格样式

学习 border-collapse/奇偶行/悬停效果 · 难度:入门 · +10XP

CSS 表格样式美化

HTML 表格默认样式比较简陋。通过 CSS 可以大幅提升表格的可读性和美观度,使其更好地展示数据。

基础表格样式

table {
  width: 100%;
  border-collapse: collapse;   /* 合并相邻边框 */
  font-family: Arial, sans-serif;
}

th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }

th { background-color: #4CAF50; color: white; font-weight: bold; }

border-collapse 属性

效果
collapse合并相邻单元格边框为单一边框(推荐)
separate每个单元格有独立边框,可用 border-spacing 控制间距

斑马纹表格

交替行颜色能显著提升数据表格的可读性:

tr:nth-child(even) {
  background-color: #f2f2f2;
}

tr:nth-child(odd) { background-color: #ffffff; }

tr:hover { background-color: #e8f4fd; transition: background-color 0.2s; }

响应式表格

在小屏幕上,传统表格宽度可能超出视口。解决方案是使用 overflow-x 包裹:

<div style="overflow-x: auto;">
  <table>
    ...
  </table>
</div>

或者使用 CSS 将表格变为纵向排列:

@media screen and (max-width: 600px) {
  table, thead, tbody, th, td, tr {
    display: block;
  }
  thead tr {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }
  td {
    position: relative;
    padding-left: 50%;
  }
  td::before {
    content: attr(data-label);
    position: absolute;
    left: 10px;
    font-weight: bold;
  }
}

固定表头

数据量大时,固定表头让用户始终能看到列名:

.table-container {
  max-height: 400px;
  overflow-y: auto;
}

.table-container thead th { position: sticky; top: 0; background: #4CAF50; z-index: 1; }

表格对齐与尺寸

/* 列宽控制 */
th:nth-child(1), td:nth-child(1) { width: 10%; }
th:nth-child(2), td:nth-child(2) { width: 60%; }

/* 数字右对齐 */ td.numeric { text-align: right; }

/* 垂直对齐 */ td { vertical-align: middle; }

综合示例

table {
  border-collapse: collapse;
  width: 100%;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border-radius: 8px;
  overflow: hidden;
}

th { background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 14px 16px; }

td { padding: 12px 16px; }

tr:not(:last-child) td { border-bottom: 1px solid #eee; }

tr:hover td { background: #f8f9ff; }

好的表格设计遵循"少即是多"原则:去除不必要的边框、使用足够的留白、通过微妙的颜色变化引导视线。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 122 篇
0 完成
🔥 0