Skip to content

CSS Table(表格)

HTML 的表格<table><tr><td><th> 等)可以通过 CSS 控制边框、单元格间距、对齐方式、背景色等,让表格更清晰、易读。

表格相关 HTML 标签简述

  • <table>:表格容器
  • <tr>:行
  • <th>:表头单元格(默认加粗、居中)
  • <td>:数据单元格

常用表格样式属性

属性适用元素作用
bordertable, th, td边框
border-collapsetable边框合并方式
border-spacingtable单元格间距(collapse 时无效)
width / heighttable, th, td宽高
text-alignth, td文字水平对齐
vertical-alignth, td文字垂直对齐
paddingth, td单元格内边距
background-colortable, tr, th, td背景色

1. 边框:border 与 border-collapse

给表格和单元格加边框时,通常先设置 border-collapse,再设 border

border-collapse(合并边框)

  • collapse:相邻单元格边框合并为一条线(常用,更整齐)。
  • separate:默认,每个单元格各自边框,中间会有空隙。
css
table {
  border-collapse: collapse;  /* 推荐:边框合并 */
}

table, th, td {
  border: 1px solid #ccc;
}

只给外框加边框

若只想让表格外围有边框,单元格之间只有分隔线,可以这样写:

css
table {
  border-collapse: collapse;
  border: 1px solid #333;
}

th, td {
  border-bottom: 1px solid #ddd;
  border-left: none;
  border-right: none;
  border-top: none;
}

或只给 thtdborder-bottom,再给 table 设一圈 border,按设计需求调整即可。


2. border-spacing(单元格间距)

仅在 border-collapse: separate 时有效,用来设置单元格之间的空隙。

css
table {
  border-collapse: separate;
  border-spacing: 10px;        /* 水平、垂直都是 10px */
  border-spacing: 8px 4px;     /* 水平 8px,垂直 4px */
}

使用 collapse 时不需要也不生效 border-spacing


3. 宽度与高度

css
table {
  width: 100%;   /* 占满容器宽度 */
  /* 或固定宽度 */
  width: 600px;
}

th, td {
  padding: 10px 12px;
}

th {
  height: 40px;  /* 表头行高(也可用 padding 控制) */
}

4. 文字对齐

  • 水平text-align: left | center | right
  • 垂直vertical-align: top | middle | bottom
css
th {
  text-align: left;
  vertical-align: middle;
}

td {
  text-align: center;
  vertical-align: top;
}

5. 内边距(padding)

让单元格内容不贴边,更易读。

css
th, td {
  padding: 10px 16px;
}

6. 背景色(斑马纹等)

表头与数据行、奇偶行可用不同背景色区分:

css
th {
  background-color: #333;
  color: white;
}

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

tr:hover {
  background-color: #f0f0f0;
}

完整示例

css
table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

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

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

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

tr:hover {
  background-color: #ddd;
}

小结

  • 边框:在 table 上设 border-collapse: collapse,再给 tablethtdborder
  • 间距border-spacing 仅在 separate 时有效;collapse 时用 padding 控制单元格内部空白。
  • 对齐text-alignvertical-align内边距padding背景background-color,可用 :nth-child:hover 做斑马纹和悬停效果。

下一节学习 CSS 盒子模型:理解元素占用的空间与 margin、padding、border 的关系。