web 开发中 table 的使用已不再像之前那样广泛。
html markup:首先使用 <table>
tag ,然后此 table 语义上分两个部分: thead
, tbody
,然后 tr
表示 table row, td
表示 table data,用 tr
表示一行。
然后第1行以及第1列的所有所有内容一般根据 Html 语义规则都应放在 <th>
内,而不是 <td>
内,一个 table 的 markup 如下:
<table>
<thead>
<tr>
<th>Chair</th>
<th>The Laid Back</th>
<th>The Worker Bee</th>
<th>The Chair 4/2</th>
</tr>
</thead>
<tbody>
<tr>
<th>Width</th>
<td>80cm</td>
<td>60cm</td>
<td>220cm</td>
</tr>
<tr>
<th>Height</th>
<td>100cm</td>
<td>110cm</td>
<td>90cm</td>
</tr>
<tr>
<th>Depth</th>
<td>70cm</td>
<td>65cm</td>
<td>80cm</td>
</tr>
<tr>
<th>Weight</th>
<td>12kg</td>
<td>22kg</td>
<td>80kg</td>
</tr>
</tbody>
</table>
没有加 CSS 的table在页面上显示如下:
使 table 在页面上居中对齐:
body {
font-family: "Inter", sans-serif;
color: #343a40;
line-height: 1;
display: flex;
justify-content: center;
}
/* 设置 table 边界: */
table {
width: 800px;
margin-top: 100px;
border: 1px solid #343a40;
}
整个表格添加边界:
td,
th {
border: 1px solid #343a40;
}
因为每一个 cell 都设置了border,所以看起来比较奇怪:
要取消上面的双重边界,使其折叠合并成单条边,需要设置 border-collapse
属性:
table {
border-collapse: collapse;
}
最终的css:
/*
SPACING SYSTEM (px)
2 / 4 / 8 / 12 / 16 / 24 / 32 / 48 / 64 / 80 / 96 / 128
FONT SIZE SYSTEM (px)
10 / 12 / 14 / 16 / 18 / 20 / 24 / 30 / 36 / 44 / 52 / 62 / 74 / 86 / 98
Main color: #087f5b
Tint1: #099268;
Grey: #343a40
footer-color: #495057;
*/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Inter", sans-serif;
color: #343a40;
line-height: 1;
display: flex;
justify-content: center;
}
table {
width: 800px;
margin-top: 100px;
font-size: 18px;
/* border: 1px solid #343a40; */
border-collapse: collapse;
}
td,
th {
/* border: 1px solid #343a40; */
padding: 16px 24px;
text-align: left;
}
thead tr {
background-color: #087f5b;
color: #fff;
}
thead th {
/* 4 列等宽 */
width: 25%;
}
tbody tr:nth-child(odd) {
background-color: #f8f9fa;
}
tbody tr:nth-child(even) {
background-color: #e9ecef;
}