The colgroup
tag is used in HTML to group one or more col
elements within a table, allowing you to style entire columns at once using CSS or attributes like span
, width
, or class
.
It must be placed directly inside a <table>
, before any rows (<tr>
).
✅ Basic Syntax
<table>
<colgroup>
<col span="1" style="background-color: #f2f2f2;">
<col span="1" style="background-color: #d9edf7;">
</colgroup>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>Apple</td>
<td>$1.00</td>
</tr>
</table>
📍 Result:
- Column 1 will have a light gray background
- Column 2 will have a light blue background
🧱 When and How to Use <colgroup>
- Use
<colgroup>
when you want to style or set properties for one or more table columns. - It works together with
<col>
tags, which target specific columns inside the group.
🧩 Attributes of <colgroup>
Attribute | Description |
---|---|
span | Specifies how many columns the group spans |
style | Applies CSS styles to the group of columns |
class | Can be used to apply external styles via CSS |
🔸 If you don’t use <col>
, you can apply span
directly to <colgroup>
:
<colgroup span="3" style="background-color: #eef;"></colgroup>
This applies the style to the first 3 columns of the table.
🎨 Styling Columns via CSS
You can use internal or external CSS to style table columns more cleanly:
<style>
.first-column {
background-color: #ffe4e1;
}
.second-column {
background-color: #e6f7ff;
}
</style>
<table>
<colgroup>
<col class="first-column">
<col class="second-column">
</colgroup>
<tr>
<th>Name</th>
<th>Score</th>
</tr>
<tr>
<td>Jane</td>
<td>90</td>
</tr>
</table>
✅ Summary
Feature | Description |
---|---|
Tag | <colgroup> |
Purpose | Groups and styles table columns |
Used with | One or more <col> tags |
Placed in | Inside <table> , before any <tr> |
Use Cases | Column styling, width control, formatting |
🚫 Limitations
- Only works on columns, not individual cells
- Some CSS properties (like
padding
) may not apply as expected through<col>