Interactive Tutorial Content
Styling tables can be repetitive. Imagine having to add a class to every single cell (td) just to make a column yellow. That creates messy, redundant code. There is a better way.
Let's start with a standard table. We have rows (tr) and cells (td). Without column definitions, the browser guesses column widths based on content.
<table border='1'>
<tr>
<td>Item</td>
<td>Price</td>
</tr>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</table>
To control columns efficiently, we use the <colgroup> container. It must be placed immediately after the opening <table> tag, before any <thead> or <tr>.
<table border='1'>
<colgroup>
</colgroup>
<tr>
<td>Item</td>
<td>Price</td>
</tr>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</table>
Inside <colgroup>, we use the <col> tag. It is a void element (self-closing). Each <col> tag represents one or more columns in the table order.
<table border='1'>
<colgroup>
<col style='background: #eef'>
<col style='background: #fee'>
</colgroup>
<tr>
<td>Item</td>
<td>Price</td>
</tr>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</table>
See the result? The styles apply to the entire column column verticaly, even though we only wrote the style once in the <col> tag.
<table border='1' style='width:100%'>
<colgroup>
<col style='background: #eef'>
<col style='background: #fee'>
</colgroup>
<tr>
<td>Item</td>
<td>Price</td>
</tr>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</table>
Checkpoint: Where must the <colgroup> tag be placed?
<table>
<thead>...</thead>
</table>
What if you want to apply the same style to 3 consecutive columns? You don't need three <col> tags. You can use the 'span' attribute.
<table border='1'>
<colgroup>
<col span='2' style='background: yellow'>
<col style='background: blue'>
</colgroup>
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
</table>
In this example, `span='2'` makes the first <col> tag cover the first AND second columns. The next <col> tag affects the third column.
<table border='1' width='100%'>
<colgroup>
<col span='2' style='background-color: #fff3cd'>
<col style='background-color: #d1e7dd'>
</colgroup>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</table>
Checkpoint: Which attribute allows a <col> tag to affect multiple columns?
<col ???='2'>
Remember, <col> is a void element. It does not have a closing tag. It sits empty waiting to style your data.
<col span='2'>
You have mastered the table columns! Now it's time to build your own grids.
<h1>Mastered!</h1>
Practice makes perfect. Use the editor below to create a table with styled columns.