colgroup HTML Table Tag
The colgroup tag specifies a group of columns in an HTML table for setting background color. With the help of using colgroup with col tags. We can achieve a similar effect with td:nth-child() CSS selectors.
A <colgroup>...</colgroup> (opening and closing tags) must be the child of a <table> element, after the <caption> element (if exists) and before any <thead>, <tbody>, <tfoot>, and <tr> elements.
The span tag attribute is used to set how many columns the rule is applied to.
Set Column Background Color
The example below demonstrates that only the background color is taken into account among the styles defined in col elements. Other syltes, like text color, opacity and font-weight are ignored.
Only the background style
is taken into account.
Colgroups in a table with caption, thead, tbody and tfoot.
Notice that the inline style and class assigned to the individual S and D td cells overwrite the style defined by the colgroup.
Colspan - Colgroup Conflict
When table cells using colspan attributes overlap more colgroup rules the whole cell will be colored to the colgroup rule applied to the left side of the cell.
In the example above, the AA cell (colspan = 2) overlaps both the white and ivory columns.
The entire cell will be colored white because that color is applied to its left side.
Column Styling Without Using Colgroups
Instead of using colgroup in our HTML we can easily reproduce the same column coloring effect using CSS styles, targetting the columns with the td:nth-child(x) CSS selector, as demonstrated below.
HTML table column styling with nth-child CSS pseudo class.
Using the same approach, we can target table rows with the tr:nth-child(x) selector.
☝ The advantage of using the nth-child technique, instead of colgroups is that we can change other styles, not just background color.
Colgroup In Div Tables
Div tables are HTML tables built with structured <div> elements. We can achieve the colgroup effect using the CSS nth-child CSS pseudo class, as demonstrated for tables under the previous heading.
Colored columns in a table made of div elements.
The online HTML table generator doesn't support the colgroup, but we can easily generate the code for a basic table. Next we can manually add colgroups in the source code, above the table rows, using the snippets below:
<col class="name" span="2">