HTML Tutorial Steps
Tables in HTML are row-oriented. You create rows <tr> and fill them with cells <td>. But what if you want to style an entire vertical column? Doing it cell by cell is tedious.
Let's start with a standard table. We have a header row and data rows. Currently, it has no specific column styling.
<table>
<tr>
<th>Item</th>
<th>Cost</th>
</tr>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</table>
To style columns, we use the <colgroup> element. It must be placed immediately after the opening <table> tag and before any <thead> or <tr>.
<table>
<colgroup>
</colgroup>
<tr>
<th>Item</th>
<th>Cost</th>
</tr>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</table>
Inside <colgroup>, we use the <col> tag. It is a self-closing void element. Each <col> represents one or more columns in the table.
<table>
<colgroup>
<col style="background-color: yellow">
</colgroup>
<tr>
<th>Item</th>
<th>Cost</th>
</tr>
...</table>
Here is the result. Notice how the entire first column 'Item' is now yellow, even though we didn't touch the <td> tags directly.
<table>
<colgroup>
<col style="background-color: #fef08a">
</colgroup>
<tr>
<th>Item</th>
<th>Cost</th>
</tr>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</table>
Checkpoint: Where must the <colgroup> tag be placed?
<table>
<thead>...</thead>
</table>
What if we want to apply the same style to multiple columns? We use the 'span' attribute. <col span='2'> will affect the next two columns.
<table>
<colgroup>
<col span="2" style="background-color: cyan">
</colgroup>
<tr>
<th>A</th><th>B</th><th>C</th>
</tr>
</table>
Using span keeps your code clean. Instead of repeating <col> tags, you group them efficiently.
<table>
<colgroup>
<col span="2" style="background-color: #a5f3fc">
</colgroup>
<tr>
<th>A</th><th>B</th><th>C</th>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</table>
Excellent! You now understand how to structure table columns semantically and visually.
<h1>Table Mastered!</h1>
Now it is your turn. Practice by building tables and defining column groups in the interactive challenges below.