CodeBlanks Logo Icon CodeBlanks

Col and colgroup

HTML course · Intermediate · Lesson 18/67

Bridge styling to columns with <col> and <colgroup>.

Col and colgroup

The <colgroup> tag groups columns in a table; it holds <col> tags. Each <col> stands for one column and bridges shared styling to it.

Instead of styling each <td> one by one, you can format a whole column from a single spot. For example, to right-align the amount column in a price list, place one <col> inside <colgroup> and add the alignment there.

<col> is a void element; it has no closing tag.

Grouping columns with col span

A <col> tag stands for a single column by default. To apply the same style to several columns at once, use the span attribute: <col span="2"> covers two columns.

For example, in a four-column table, to style the last three columns the same way you can write <colgroup><col><col span="3"></colgroup>. This keeps the code short and consistent.

Exercise Build a table with colgroup and col span

Write a <table>. Put a non-empty <caption> inside. After caption add a <colgroup> holding one <col> and one <col span="2">. Then add <thead> with a row of <th scope="col">, and <tbody> with at least one row of <td>.

Show example solution
<table>
  <caption>Monthly Sales Report</caption>
  <colgroup>
    <col>
    <col span="2">
  </colgroup>
  <thead>
    <tr>
      <th scope="col">Month</th>
      <th scope="col">Product</th>
      <th scope="col">Revenue</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Jan</td>
      <td>Headphones</td>
      <td>$3,200</td>
    </tr>
  </tbody>
</table>

Test yourself

  1. What is the core role of colgroup?

    • Merge cells together
    • Bridge shared styling to columns
    • Add a title to the table
    • Make the table scrollable
    Show answer

    Bridge shared styling to columns — Correct. colgroup bridges shared styling to columns through the col tags it holds.

  2. Add a colgroup to the table

    <table>
      <caption>Monthly sales</caption>
      ____>
        <col>
        <col span="2">
      </colgroup>
    </table>
    Show answer
    <table>
      <caption>Monthly sales</caption>
      <colgroup>>
        <col>
        <col span="2">
      </colgroup>
    </table>
  3. Match each tag to its role

    colgroup
    Groups columns
    col
    Stands for a single column
    span attribute
    Covers several columns
    caption
    Titles the table

All lessons in Intermediate