HTML Table Colgroup :


The <colgroup> element in HTML is used to group together a set of <col> elements within a table. It allows you to apply styles and attributes to multiple columns simultaneously, making it a convenient way to manage the appearance and behavior of columns in a table.

Here's a basic example of how to use <colgroup>:

<!DOCTYPE html>
<html>
<head>
    <title>Table with Colgroup</title>
    <style>
        /* Optional CSS for better styling */
        table {
            border-collapse: collapse;
            width: 50%;
            margin: 20px;
        }
        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: left;
        }
    </style>
</head>
<body>

<table>
    <colgroup>
        <col style="background-color: lightblue;">
        <col span="2" style="background-color: lightgreen;">
    </colgroup>
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
        <th>Header 3</th>
    </tr>
    <tr>
        <td>Data 1,1</td>
        <td>Data 1,2</td>
        <td>Data 1,3</td>
    </tr>
    <tr>
        <td>Data 2,1</td>
        <td>Data 2,2</td>
        <td>Data 2,3</td>
    </tr>
</table>

</body>
</html>

In this example:

  • The <colgroup> element wraps a set of <col> elements.
  • Each <col> element can have various attributes and styles applied to it. In this case, background colors are applied to different columns.
  • The <col span="2"> attribute in the second <col> element indicates that it should span two columns.


Using <colgroup> and <col> allows you to apply styles to columns in a more structured way. This can be particularly useful when you want to apply common styling to multiple columns without repeating the styles for each individual <th> or <td> element.

Post a Comment

Previous Post Next Post

Popular Items