介绍
HTML <colgroup> 标签用于为 HTML 表格中的一个或多个列应用各种样式。使用 <colgroup> 标签可以避免在表格的每个单元格中定义样式的繁琐操作。通过该标签的 span 属性,你可以将样式应用到指定的列上。
在本实验中,你将学习如何使用 HTML <colgroup> 标签创建带有彩色列的表格。
注意:你可以在
index.html中练习编码,并学习如何在 Visual Studio Code 中编写 HTML。请点击右下角的“Go Live”以在端口 8080 上运行 Web 服务。然后,你可以刷新 Web 8080 标签以预览网页。
创建 HTML 表格
首先,创建一个 HTML 表格,你将使用 <colgroup> 标签为其应用样式。将以下代码添加到你的 HTML 文件中:
<!doctype html>
<html>
<head>
<title>Colored Table</title>
</head>
<body>
<table border="1">
<caption>
Colored Table
</caption>
<colgroup>
<col style="background-color: gray;" />
<col style="background-color: lightblue;" />
<col style="background-color: lightgreen;" />
</colgroup>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
<td>Row 1, Column 3</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
<td>Row 2, Column 3</td>
</tr>
</tbody>
</table>
</body>
</html>
以上代码创建了一个边框为 1 的表格,并带有标题 "Colored Table"。<colgroup> 标签包含三个 <col> 标签,分别为三列应用了不同的颜色。<thead> 标签包含三个 <th> 标签,分别表示三列的标题。而 <tbody> 标签包含两行,每行有三列。
编写 CSS 以实现更好的样式
在这一步中,我们将使用 CSS 为上面创建的表格应用样式。
将以下 CSS 代码添加到你的 HTML 文件中:
<!doctype html>
<html>
<head>
<title>Colored Table</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #4169e1;
color: white;
}
</style>
</head>
<body>
<table border="1">
<caption>
Colored Table
</caption>
<colgroup>
<col style="background-color: gray;" />
<col style="background-color: lightblue;" />
<col style="background-color: lightgreen;" />
</colgroup>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
<td>Row 1, Column 3</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
<td>Row 2, Column 3</td>
</tr>
</tbody>
</table>
</body>
</html>
在你的 index.html 文件中查看完成的代码。你应该能够看到一个三列的表格,每列都有不同的颜色。
总结
HTML <colgroup> 标签用于为 HTML 表格中的一个或多个列应用各种样式,从而避免在表格的每个单元格中定义样式的繁琐操作。在本实验中,你学习了如何使用 <colgroup> 标签创建带有彩色列的表格,并通过 CSS 为其应用样式。



