样式化表格—CSS学习笔记

314 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情


前言

在使用展示数据的时候,常常会因表格不够规整精美而烦恼。当然,你可以使用ui框架,但大多数时候使用css样式化表格是一个好的选择。

样式化表格

html表格

首先我们要准备一个表格来展示一些数据。

<table>
<caption>
    学生信息表
</caption>
<thead>
    <tr>
        <th scope="col">学号</th>
        <th scope="col">姓名</th>
        <th scope="col">班级</th>
        <th scope="col">成绩</th>
    </tr>
</thead>
<tbody>
    <tr>
        <th scope="row">060201</th>
        <td>张三</td>
        <td>六年二班</td>
        <td>98</td>
    </tr>
    <tr>
        <th scope="row">060202</th>
        <td>李四</td>
        <td>六年二班</td>
        <td>95</td>
    </tr>
    <tr>
        <th scope="row">060203</th>
        <td>王五</td>
        <td>六年二班</td>
        <td>92</td>
    </tr>
</tbody>
<tfoot>
    <tr>
        <th scope="row" colspan="3">班级总分</th>
        <td colspan="1">285</td>
    </tr>
</tfoot>
</table>

效果:

image.png

但我们可以看到默认的样式空间全靠内容撑开,显得比较拥挤且不美观,接下来我们便通过css来样式化。

样式化

排版

要改变其拥挤的排列,首先要给表格一个宽度且每列固定宽度,再给内容一些边距,再用边框将表格包围显得其有边界。

table {
  table-layout: fixed;
  width: 60%;
  border: 2px solid black;
}
​
thead th:nth-child(1) {
  width: 35%;
}
​
thead th:nth-child(2) {
  width: 25%;
}
​
thead th:nth-child(3) {
  width: 25%;
}
​
thead th:nth-child(4) {
  width: 15%;
}
​
th, td {
  padding: 20px;
}

其中table-layout属性有auto、fixed两种状态。auto便是表格列的宽度会随内容变化,这样可能造成每列的宽度都不一致。而fixed可以根据列标题单元格的宽度来规定列的宽度。上文的thead th:nth-child(*)便表示thead后代所有th兄弟元素,*即代表顺序,这里便通过这个选择器列表匹配列标题的单元格来分别设置宽度。

效果:

image.png

标题与内容字体

排版完以后,表格的字体应居中,标题的字体应与内容有差别。当然,也可以修改字体以更适合表格的内容显示。

caption {
    font-weight: bold;
    font-size: 200%;
    color: darkblue;
}
​
table{
    text-align: center;
}
​
thead th,
tfoot th {
    font-weight: bold;
    text-shadow: 1px 1px 1px grey;
}

image.png

图形和颜色

现在可以给表格加些斑马纹,并给标题单元格加个背景颜色。

thead th,
tfoot th,
tfoot td {
    background: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.5));
}
/*奇数行*/
tbody tr:nth-child(odd) {
    background-color: #8133ff;
    color: #fff;
}
/*偶数行*/
tbody tr:nth-child(even) {
    background-color: #95d2e4;
}

image.png

现在效果差不多,但看到列行之间会有默认的边框间隙。这时候在整体表格设置border-collapse:collapse;就可以合并为一个单一的边框,我们的表格也就完成样式化了。

image.png