Imagine you have a table with 50 rows, and you want the third column representing "Total Value" to have a light green background color. Writing an inline style or class tag on 50 separate <td> elements is exhausting and bad practice. Instead, HTML offers a way to pre-define the visual aesthetic of whole vertical stacks: the <colgroup> element.
The <colgroup> block must sit at the very top of your table block—immediately after the opening <table> tag, but before any rows (tr) or headers (thead) are declared.
Inside the group, you place individual <col> elements that represent mathematical slices of your table from left to right. Even if you only want to style the 3rd column, you must account for the ones before it.
<table style="width:100%; border-collapse: collapse;">
<colgroup>
<!-- Column 1: No rules applied -->
<col>
<!-- Column 2: Highlights the row in a subtle yellow tone -->
<col style="background-color: #fffae6;">
<!-- Column 3: No rules applied -->
<col>
</colgroup>
<!-- Rows follow normally... -->
<tr>
<th>Student Name</th>
<th>Final Grade</th>
<th>Attendance</th>
</tr>
<tr>
<td>Jennifer</td>
<td>A-</td>
<td>94%</td>
</tr>
</table>
| Student Name | Final Grade | Attendance |
|---|---|---|
| Jennifer | A- | 94% |
| Marcus | B+ | 88% |
What if you want to highlight 4 consecutive columns with a gray background? Typing out 4 identical <col> tags works, but utilizing the span attribute makes your code much cleaner. By adding span="4", that single tag will project its styling across four sequential columns simultaneously.
<!-- Example: First column is basic, the next 3 are grouped orange -->
<colgroup>
<col>
<col span="3" style="background-color: #ffe8cc;">
</colgroup>