Html Table Colgroup


The <colgroup> element in HTML is used to group one or more columns in a table for formatting purposes. It allows you to apply styles or attributes to entire columns of the table rather than to individual <td> or <th> elements.


Syntax

The basic syntax for <colgroup> is:

<table>
  <colgroup>
    <col>
    <col>
    ...
  </colgroup>
  ...
</table>

Each <col> element inside the <colgroup> represents a column in the table. You can also specify attributes for the <colgroup> and <col> elements to style the columns.


Attributes

  • span: Specifies the number of columns the <col> element should span.
  • style: CSS styles can be applied directly to the <col> or <colgroup>.


Basic <colgroup> Usage

<!DOCTYPE html>
<html>
<head>
  <style>
    .first-column {
      background-color: #f2f2f2;
    }
    .second-column {
      background-color: #e0e0e0;
    }
  </style>
</head>
<body>

<table border="1">
  <colgroup>
    <col class="first-column">
    <col class="second-column">
  </colgroup>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John</td>
    <td>30</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>25</td>
  </tr>
</table>

</body>
</html>

In this example, the first column has a light gray background (#f2f2f2), and the second column has a slightly darker gray background (#e0e0e0).


 Using the span Attribute

<!DOCTYPE html>
<html>
<head>
  <style>
    .highlight {
      background-color: yellow;
    }
  </style>
</head>
<body>

<table border="1">
  <colgroup>
    <col span="2" class="highlight">
    <col>
  </colgroup>
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Location</th>
  </tr>
  <tr>
    <td>John</td>
    <td>30</td>
    <td>USA</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>25</td>
    <td>UK</td>
  </tr>
</table>

</body>
</html>

In this example, the span="2" attribute on the first <col> element applies the highlight class (yellow background) to the first two columns. The third column remains unstyled.


Complex Styling with Multiple <colgroup>

<!DOCTYPE html>
<html>
<head>
  <style>
    .group1 {
      background-color: #ffcccc;
    }
    .group2 {
      background-color: #ccffcc;
    }
  </style>
</head>
<body>

<table border="1">
  <colgroup class="group1">
    <col>
    <col>
  </colgroup>
  <colgroup class="group2">
    <col>
  </colgroup>
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Location</th>
  </tr>
  <tr>
    <td>John</td>
    <td>30</td>
    <td>USA</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>25</td>
    <td>UK</td>
  </tr>
</table>

</body>
</html>

In this example, two <colgroup> elements are used. The first group has a red background (#ffcccc) for the first two columns, and the second group has a green background (#ccffcc) for the third column.

Using <colgroup> and <col>, you can effectively manage and style table columns in a more organized and scalable way.