HTML <colgroup>标签用于描述表中一列或多列的集合,以便进行格式设置。与其复制每列和每行的样式,不如将样式应用于整列。
要声明列的不同特征,请在 <col> 标签中使用 <colgroup>标签。 <colgroup>标签必须是 <table> 元素的子元素,位于任何 <caption> 元素之后,以及任何 <thead>、<tbody>、<tfoot> 和 <tr> 元素之前。
语法
<colgroup>...</colgroup>
属性
<colgroup>标签支持 HTML 的 全局属性 和 事件属性。下面列出了一些特定属性。
属性 | 值 | 描述 |
---|---|---|
span | number | 指定 <col> 元素跨越的连续列数。 |
align | left right center justify |
指定文本内容的对齐方式(已弃用)。 |
bgcolor | color | 指定每个列单元格的背景色(已弃用)。 |
char | character | 指定内容与每个列单元格的字符的对齐方式(已弃用)。 |
charoff | number | 指定用于偏移列单元格内容与 char 属性指定的对齐字符的字符数(已弃用)。 |
valign | baseline bottom middle top |
指定每个列单元格的垂直对齐方式(已弃用)。 |
<colgroup>标签示例
下面的示例将说明 <colgroup>标签的用法。在何处、何时以及如何使用 <colgroup>标签来提供有关列的信息。
在表中使用 <colgroup>标签
以下示例,我们将在表中使用 <colgroup>标签。
<!DOCTYPE html>
<html>
<body>
<table border="1">
<colgroup>
<col style="background-color:#ABEBC6">
<col style="background-color:#BB8FCE">
</colgroup>
<tr>
<th>Roll.No</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>Maya</td>
</tr>
<tr>
<td>2</td>
<td>Surya</td>
</tr>
<tr>
<td>3</td>
<td>Ram</td>
</tr>
</table>
</body>
</html>
指定连续列
考虑另一种情况,我们将使用 span 属性和 <colgroup> 标签。
<!DOCTYPE html>
<html>
<style>
table,
th,
td {
border: 1.5px solid #DE3163;
}
</style>
<body>
<table>
<colgroup>
<col span="2" style="background-color:#F9E79F">
</colgroup>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
<tr>
<td>5-Star</td>
<td>$10</td>
</tr>
<tr>
<td>Dairy-Milk</td>
<td>$50</td>
</tr>
<tr>
<td>Kitkat</td>
<td>$20</td>
</tr>
</table>
</body>
</html>
设置并列组元素的样式
在以下示例中,我们将通过传递一个空的 <col> 将 CSS 应用于表格的中间,而不应用之前列的样式。
<!DOCTYPE html>
<html>
<style>
table,
th,
td {
border: 1.5px solid #85C1E9;
border-collapse: collapse;
}
</style>
<body>
<table style="width: 50%;">
<colgroup>
<col span="1">
<col span="1" style="background-color: #ABEBC6 ">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
</table>
</body>
</html>
隐藏列
让我们看另一个示例,我们将使用 visibility:collapse 属性隐藏该列。
<!DOCTYPE html>
<html>
<style>
table,
th,
td {
border: 1.5px solid #DE3163;
border-collapse: collapse;
}
</style>
<body>
<table style="width: 100%;">
<colgroup>
<col span="2">
<col span="3" style="visibility: collapse">
</colgroup>
<tr>
<th>ID</th>
<th>Employee</th>
<th>Department</th>
<th>Age</th>
</tr>
<tr>
<td>112</td>
<td>Rahul</td>
<td>IT</td>
<td>22</td>
</tr>
<tr>
<td>113</td>
<td>Ram</td>
<td>Associate</td>
<td>24</td>
</tr>
<tr>
<td>114</td>
<td>Maya</td>
<td>HR</td>
<td>30</td>
</tr>
<tr>
<td>115</td>
<td>Rahul</td>
<td>BPO</td>
<td>23</td>
</tr>
</table>
</body>
</html>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | Yes | Yes | Yes | Yes | Yes |