Should I use <colgroup> and <col>, and if so, why and how?

Roger G. Zapata picture Roger G. Zapata · Jan 28, 2017 · Viewed 13.3k times · Source

I've been trying to use properly the colgroup and the col tags but I don't get it. I read the specification and all that but I don't understand its purpose or how to implement it.

Answer

Adam picture Adam · Jan 29, 2017

A colgroup is used in a table element to help understand complex hierarchy of information within tables with irregular headers.

The WAI has a complete information page about how to handle such situation: Tables with irregular headers and understand the use of col and colgroup

To associate the first-level headers properly with all cells of both columns, the column structure needs to be defined at the beginning of the table. A <col> element identifies each column, beginning on the left. If a header spans two or more columns, use a <colgroup> element instead of that number of <col> elements, and the number of columns spanned is noted in the span attribute.

That being said, the best use case for those elements is for styling columns without repeating the style or class attributes:

<table>
  <colgroup>
    <col style="background-color:red">
    <col style="background-color:yellow">
    <col style="background-color:blue">
  </colgroup>
  <tr>
    <th>First</th>
    <th>Second</th>
    <th>Third</th>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
</table>