表格边框
如需在 CSS 中设置表格边框,请使用 border 属性。
下例为 <table>、<th> 和 <td> 元素规定了黑色边框:
table, th, td {
border: 1px solid black;
}
注意:上例中的表格拥有双边框。这是因为 table 和 <th> 和 <td> 元素都有单独的边框。
合并表格边框
border-collapse 属性设置是否将表格边框折叠为单一边框:
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
如果只希望表格周围有边框,则仅需为 <table> 指定 border 属性:
table {
border: 1px solid black;
}
表格宽度和高度
表格的宽度和高度由 width 和 height 属性定义。
下例将表的宽度设置为 100%,将 <th> 元素的高度设置为 50px:
table {
width: 100%;
}
th {
height: 50px;
}
水平对齐
text-align 属性设置 <th> 或 <td> 中内容的水平对齐方式(左、右或居中)。
默认情况下,<th> 元素的内容居中对齐,而 <td> 元素的内容左对齐。
要使 <td> 元素的内容也居中对齐,请使用 text-align: center:
th {
text-align: center;
}
表格内边距
如需控制边框和表格内容之间的间距,请在 <td> 和 <th> 元素上使用 padding 属性:
th, td {
padding: 15px;
text-align: left;
}
水平分隔线
向 <th> 和 <td> 添加 border-bottom 属性,以实现水平分隔线:
th, td {
border-bottom: 1px solid #ddd;
}
可悬停表格
在 <tr> 元素上使用 :hover 选择器,以突出显示鼠标悬停时的表格行:
tr:hover {background-color: #f5f5f5;}
鼠标放在某一行表格上,这行表格颜色 变更为:#f5f5f5
条状表格
为了实现斑马纹表格效果,请使用 nth-child() 选择器,并为所有偶数(或奇数)表行添加 background-color:
tr:nth-child(even) {background-color: #f2f2f2;}
表格颜色
下例指定了 <th> 元素的背景颜色和文本颜色:
th {
background-color: #4CAF50;
color: white;
}
响应式表格
如果屏幕太小而无法显示全部内容,则响应式表格会显示水平滚动条:
| First Name | Last Name | Points | Points | Points | Points | Points | Points | Points | Points | Points | Points |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Bill | Gates | 50 | 50 | 50 | 50 | 50 | 50 | 50 | 50 | 50 | 50 |
| Steve | Jobs | 94 | 94 | 94 | 94 | 94 | 94 | 94 | 94 | 94 | 94 |
| Elon | Musk | 67 | 67 | 67 | 67 | 67 | 67 | 67 | 67 | 67 | 67 |
在 <table> 元素周围添加带有 overflow-x:auto 的容器元素(例如 <div>),以实现响应式效果:
<div style="overflow-x:auto;">
<table>
... table content ...
</table>
</div>
注释:在 OS X Lion(在 Mac 上)中,滚动条默认情况下是隐藏的,并且仅在使用时显示(即使设置了 "overflow:scroll")。
CSS 表格属性
| 属性 | 描述 |
|---|---|
| border | 简写属性。在一条声明中设置所有边框属性。 |
| border-collapse | 规定是否应折叠表格边框。 |
| border-spacing | 规定相邻单元格之间的边框的距离。 |
| caption-side | 规定表格标题的位置。 |
| empty-cells | 规定是否在表格中的空白单元格上显示边框和背景。 |
| table-layout | 设置用于表格的布局算法。 |