HTML 表格列

HTMLHTMLBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

HTML <col> 标签用于单独定义表格中每一列的属性。在本实验中,你将学习如何使用 <col> 标签来为 HTML 表格的列设置样式。

注意:你可以在 index.html 中练习编码,并学习如何在 Visual Studio Code 中编写 HTML。请点击右下角的 'Go Live' 以在端口 8080 上运行 Web 服务。然后,你可以刷新 Web 8080 标签以预览网页。



Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL html(("HTML")) -.-> html/TablesGroup(["Tables"]) html(("HTML")) -.-> html/AdvancedElementsGroup(["Advanced Elements"]) html/TablesGroup -.-> html/tables("Table Structure") html/TablesGroup -.-> html/complex_tbl("Complex Tables") html/TablesGroup -.-> html/tbl_access("Table Accessibility") html/AdvancedElementsGroup -.-> html/custom_attr("Custom Data Attributes") subgraph Lab Skills html/tables -.-> lab-70726{{"HTML 表格列"}} html/complex_tbl -.-> lab-70726{{"HTML 表格列"}} html/tbl_access -.-> lab-70726{{"HTML 表格列"}} html/custom_attr -.-> lab-70726{{"HTML 表格列"}} end

创建 HTML 表格

在你的项目 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> 标签通过使用值为 2span 属性,一次性针对两列。

使用全局属性和事件属性

<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 和伪元素为表格列添加单位。