HTML <colgroup> Tag

The HTML <colgroup> tag represents a group of one or more columns within a table in an HTML document.

It can be used to apply styles across one or more columns. This can be handy because it eliminates the need to apply the styles at the individual <td> level.

The <colgroup> tag must be used as a child of a <table> element, after any <caption> elements and before any <thead>, <tbody>, <tfoot>, and <tr> elements.

Syntax

The <colgroup> tag is written as <colgroup></colgroup>. It can have either a span attribute, which specifies how many columns to span, or it can contain one or more <col> tags, which can be used to represent different columns within the <colgroup> element.

Like this:

Or this:

Examples

Basic tag usage

In this example we use the <colgroup> tag to span the first two columns of a three column table (and we apply a background color to them).

Multiple <colgroup> Elements

You can use multiple <colgroup> tags to represent various column groups across a table. Here, we use two <colgroup> elements; the first represents the first two columns, while the second represents the third column.

The <col> Tag

If you need to apply different properties to a column within a colgroup, you can use the <col> tag within the <colgroup> tag.

Like this:

Attributes

Attributes can be added to an HTML element to provide more information about how the element should appear or behave.

The <colgroup> element accepts the following attributes.

AttributeDescription
spanSpecifies how many columns to span. This attribute should not be used if there are any <col> elements within this <colspan> tag. This attribute's value must be a valid non-negative integer greater than zero.

Global Attributes

The following attributes are standard across all HTML elements. Therefore, you can use these attributes with the <colgroup> tag , as well as with all other HTML tags.

For a full explanation of these attributes, see HTML 5 global attributes.

Event Handlers

Event handler content attributes enable you to invoke a script from within your HTML. The script is invoked when a certain "event" occurs. Each event handler content attribute deals with a different event.

Most event handler content attributes can be used on all HTML elements, but some event handlers have specific rules around when they can be used and which elements they are applicable to.

For more detail, see HTML event handler content attributes.