HTML <colgroup>, <col> tags

The HTML <colgroup> tag specifies properties for a group of columns within a table. If you need to apply different properties to a column within a colgroup, you can use the HTML  <col> tag within the colgroup tag.

  • The <colgroup> element sets a group of columns in HTML tables.
  • This element is a parent of <col>.
  • The <table> element is a parent of <colgroup> in HTML.
  • The <colgroup> element specifies a common formatting style for a group of HTML columns.

The HTML <col> tag allows grouping together attribute specifications for table columns. It does not group columns together structurally – that is the role of the <colgroup> element.

HTML Table Source Code 3.1.4 shows sample code of HTML table with colgroup.


<table style="border:1px solid black">
    <colgroup>
        <col span="1" style="background-color: cornsilk">
        <col span="1" style="background-color: bisque">
    </colgroup>
    <tr>
        <th style="border-style: solid; border-width: 1px; border-color: black">Price</th>         
        <th style="border-style: solid; border-width: 1px; border-color: black">Item</th>
        <th style="border-style: solid; border-width: 1px; border-color: black">Quantity</th>
    </tr>
    <tr>
        <td style="border-style: solid; border-width: 1px; border-color: black">100</td>
        <td style="border-style: solid; border-width: 1px; border-color: black">Peanut Butter</td>
        <td style="border-style: solid; border-width: 1px; border-color: black">2</td>
    </tr>
</table>


   Note: a <col> element can be used within <colgroup> to define a different property for a single column in the group.

This will produce the following output:


The span attribute specifies a number of columns, indicating the span of a column group. This attribute could either be used in the <col> or <colgroup> tags as shown below and in the previous code.

HTML Table Source Code 3.1.4 shows sample code of HTML table emphasizing span attribute.


<table>
    <colgroup span="2" style="background-color: darkgray"> </colgroup>
    <tr>
        <th>Name</th>
        <th>City</th>  
    </tr>
    <tr>
        <td>James</td>
        <td>New York</td>
    </tr>
    <tr>
        <td>Laura</td>
        <td>Chicago</td>
    </tr>
</table>

This will produce the following output:



   Remember: always use <colgroup> with span when there are no <col> elements.