HTML表格样式

使用 CSS 使您的表格看起来更好看。

交错条纹

如果您在每隔一个表格行添加背景颜色,您将获得漂亮的斑马条纹效果, 该效果可以让你在看很长的表格是更好的定位每行数据。

要设置其他表格行元素的样式,请使用如下 :nth-child(even) 选择器:


示例

<style>
table, th, td {
  border: 1px solid black;
}
tr:nth-child(even) {  background-color: #D6EEEE;}
</style>
<table>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>身高</th>

    </tr>
    <tr>
        <td>小白</td>
        <td>11</td>
        <td>男</td>
        <td>181</td>

    </tr>
    <tr>
        <td>教程</td>
        <td>22</td>
        <td>女</td>
        <td>160</td>

    </tr>
</table>

注意:如果您使用 (odd) 而不是 (even) ,样式将出现在第 1,3,5 等行而不是 2,4,6 等。

HTML 表格 - 纵向斑马条纹

要制作垂直斑马条纹,请每隔一列设置样式,而不是每隔 一行设置样式。

像这样设置 :nth-child(even) 表数据元素:


示例

<style>
table, th, td {
  border: 1px solid black;
}
td:nth-child(even), th:nth-child(even) {  background-color: #D6EEEE;}
</style>
<table>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>身高</th>

    </tr>
    <tr>
        <td>小白</td>
        <td>11</td>
        <td>男</td>
        <td>181</td>

    </tr>
    <tr>
        <td>教程</td>
        <td>22</td>
        <td>女</td>
        <td>160</td>

    </tr>
</table>

注意: 如果您想在标题和常规表格单元格上都设置样式,请将 :nth-child() 选择器放在和 th 元素上。 td

结合纵向和水平的斑马条纹

您可以结合上面两个示例中的样式,并且每隔一行和每隔一列都会有条纹。

如果您使用透明颜色,您将获得重叠效果。

使用一种 rgba() 颜色来指定颜色的透明度:


示例

<style>
table, th, td {
  border: 1px solid black;
}
tr:nth-child(even) {  background-color: rgba(150, 212, 212, 0.4); } th:nth-child(even),td:nth-child(even) {  background-color: rgba(150, 212, 212, 0.4);}
</style>
<table>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>身高</th>

    </tr>
    <tr>
        <td>小白</td>
        <td>11</td>
        <td>男</td>
        <td>181</td>

    </tr>
    <tr>
        <td>教程</td>
        <td>22</td>
        <td>女</td>
        <td>160</td>

    </tr>
</table>

水平分隔线

如果您仅在每个表格行的底部指定边框,您将拥有一个带有水平分隔线的表格。

border-bottom 属性添加到所有 tr 元素以获得水平分隔符:


示例

<style>
table, th, td {
  border: 1px solid black;
}
tr {  border-bottom: 1px solid #ddd;}
</style>
<table>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>身高</th>

    </tr>
    <tr>
        <td>小白</td>
        <td>11</td>
        <td>男</td>
        <td>181</td>

    </tr>
    <tr>
        <td>教程</td>
        <td>22</td>
        <td>女</td>
        <td>160</td>

    </tr>
</table>

悬停表

使用 :hover 选择器 tr 在鼠标悬停时突出显示表格行:


示例

<style>
table, th, td {
  border: 1px solid black;
}
tr:hover {background-color: #D6EEEE;}
</style>
<table>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>身高</th>

    </tr>
    <tr>
        <td>小白</td>
        <td>11</td>
        <td>男</td>
        <td>181</td>

    </tr>
    <tr>
        <td>教程</td>
        <td>22</td>
        <td>女</td>
        <td>160</td>

    </tr>
</table>
此页面最后编辑于2022年8月4日 (星期四) 22:54。