HTML Table Colgroup

      Comments Off on HTML Table Colgroup
Spread the love

HTML Table Colgroup:

HTML table is a common way to present data in a structured manner. The table element contains several elements that help to style and format the table. One of these elements is the colgroup element. The colgroup element is used to define a group of columns within a table. This element allows you to apply styles and formatting to multiple columns at once.

Syntax:

The syntax for the colgroup element is as follows:

html
<table>
  <colgroup>
    <col>
    <col>
  </colgroup>
  <tbody>
    <tr>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

The colgroup element must be placed immediately after the opening table tag and before the tbody, thead, or tfoot element.

Attributes:

The colgroup element has two attributes: span and width. The span attribute specifies the number of columns to apply the style or formatting to, while the width attribute specifies the width of the column.

Example:

html
<table>
  <colgroup span="2" style="background-color: #f2f2f2;"></colgroup>
  <tr>
    <td>John</td>
    <td>Doe</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>Doe</td>
  </tr>
</table>

In the above example, the style attribute is used to set the background color of the first two columns to #f2f2f2.

Colgroup and Col Elements:

The colgroup element is often used in conjunction with the col element. The col element defines a single column within a colgroup. You can apply styles and formatting to individual columns using the col element. The span attribute of the col element is used to specify the number of columns the element applies to.

Example:

html
<table>
  <colgroup>
    <col span="1" style="background-color: #f2f2f2;">
    <col span="2">
  </colgroup>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>Doe</td>
    <td>22</td>
  </tr>
</table>

In the above example, the first column is set to have a background color of #f2f2f2 using the col element. The second and third columns are left unstyled.

Conclusion:

The colgroup element is a useful tool for formatting and styling multiple columns within an HTML table. By using the span and width attributes, you can apply styles and formatting to multiple columns at once.