介绍
HTML <col>
标签用于单独定义表格中每一列的属性。在本实验中,你将学习如何使用 <col>
标签来为 HTML 表格的列设置样式。
注意:你可以在
index.html
中练习编码,并学习如何在 Visual Studio Code 中编写 HTML。请点击右下角的 'Go Live' 以在端口 8080 上运行 Web 服务。然后,你可以刷新 Web 8080 标签以预览网页。
HTML <col>
标签用于单独定义表格中每一列的属性。在本实验中,你将学习如何使用 <col>
标签来为 HTML 表格的列设置样式。
注意:你可以在
index.html
中练习编码,并学习如何在 Visual Studio Code 中编写 HTML。请点击右下角的 'Go Live' 以在端口 8080 上运行 Web 服务。然后,你可以刷新 Web 8080 标签以预览网页。
在你的项目 index.html
文件中,添加以下代码以创建一个基本的 HTML 表格:
<table>
<colgroup>
<col />
<col />
<col />
</colgroup>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<td>Product 1</td>
<td>$10</td>
<td>5</td>
</tr>
<tr>
<td>Product 2</td>
<td>$20</td>
<td>10</td>
</tr>
</table>
<col>
标签为列设置样式现在,让我们添加 <col>
标签来为表格的列设置样式。将上述代码中的 <colgroup>
标签替换为以下代码:
<colgroup>
<col style="background-color: lightblue" />
<col style="background-color: lightgreen" />
<col style="background-color: lightpink" />
</colgroup>
在上面的代码中,我们添加了带有 style
属性的 <col>
标签,为表格的每一列应用不同的背景颜色。
span
属性你可以使用 <col>
标签的 span
属性来一次性针对多个列。例如:
<colgroup>
<col style="background-color: lightblue" />
<col span="2" style="background-color: lightgreen" />
</colgroup>
在这个例子中,第二个 <col>
标签通过使用值为 2
的 span
属性,一次性针对两列。
<col>
标签支持全局属性(Global attributes)和事件属性(Event attributes),以便为表格列添加额外的样式和功能。例如,你可以使用 class
属性为列添加 CSS 类:
<colgroup>
<col style="background-color: lightblue" class="product-name" />
<col span="2" style="background-color: lightgreen" class="price-quantity" />
</colgroup>
现在,你可以使用 .product-name
和 .price-quantity
类为表格列应用 CSS 样式。
你可以使用 ::before
和 ::after
伪元素以及 CSS 为表格列添加单位,例如货币或百分比值。例如:
<colgroup>
<col style="background-color: lightblue" class="product-name" />
<col span="2" style="background-color: lightgreen" class="price-quantity" />
</colgroup>
td::before {
content: "$";
}
td:last-of-type::after {
content: "%";
}
在上面的代码中,::before
伪元素在前两列的值前添加美元符号,而 ::after
伪元素在最后一列的值后添加百分比符号。
在本实验中,你学习了如何使用 HTML <col>
标签为 HTML 表格的列设置样式。你还学习了如何使用 span
属性、全局属性(Global attributes)和事件属性(Event attributes)为表格列添加额外的样式和功能。最后,你学习了如何使用 CSS 和伪元素为表格列添加单位。