Styling HTML Table Columns with `` and ` `
Learn to style individual columns in your HTML tables using the powerful `
Styling Table Columns with HTML `colgroup`
The HTML <colgroup>
element allows you to apply styles to specific columns in an HTML table, enhancing visual organization and presentation.
Using `colgroup` and `col`
The <colgroup>
element acts as a container for column specifications. Inside <colgroup>
, you use one or more <col>
elements, each defining styles for one or more columns.
The span
attribute in <col>
determines how many columns the style applies to. The style
attribute contains the CSS rules.
Example: Styling the First Two Columns
<table>
<colgroup>
<col style="background-color:#f0f0f0;">
<col style="background-color:#ddd;">
<colgroup>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</table>
This styles the first two columns with different background colors.
Important Note: <colgroup>
must be a child of <table>
and placed *before* any other table elements (<thead>
, <tbody>
, <tfoot>
, <tr>
, etc.).
Allowed CSS Properties
Only a limited set of CSS properties are effective within the <col>
element:
width
visibility
background
properties (e.g.,background-color
)border
properties
Other CSS properties will be ignored.
Styling Multiple Columns with Different Styles
To style multiple columns with different styles, add multiple <col>
elements within the <colgroup>
element.
Example: Multiple Col Elements
<table>
<colgroup>
<col style="background-color:#f0f0f0;">
<col style="background-color:#ddd;" span="2">
</colgroup>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</table>
Styling Columns in the Middle of a Table
To style columns that aren't at the beginning of the table, you'll need empty <col>
elements (without styles) to represent the columns you want to skip.
Example: Styling Middle Columns
<table>
<colgroup>
<col>
<col>
<col style="background-color:yellow;">
</colgroup>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</table>
Hiding Columns
You can hide columns using the visibility: collapse;
CSS property within the <col>
style attribute.
Example: Hiding Columns
<col style="visibility:collapse;">