Table Colgroup
The <colgroup>
and <col>
elements allow you to group columns structurally and apply styles or attributes to them collectively. This is useful for applying uniform widths, backgrounds, or other properties to entire columns without repeating CSS on each cell.
Key Topics
Using Colgroup
Example: Define a group of columns and apply attributes to them.
<table>
<colgroup>
<col style="background:#f9f9f9;">
<col style="background:#e9e9e9;">
</colgroup>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Styling Columns
Example: Apply widths or text-align to all cells in a column via <col>
.
<colgroup>
<col style="width:150px; text-align:right;">
<col style="width:100px; text-align:center;">
</colgroup>
Colgroup Example
This example demonstrates how <colgroup>
can simplify styling for entire columns. A full code sample is provided below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Colgroup Example</title>
<style>
table {
border-collapse: collapse;
margin:0 auto;
width:50%;
}
td {
border:1px solid #ccc;
padding:5px;
}
</style>
</head>
<body>
<h1>Sales Data</h1>
<table>
<colgroup>
<col style="width:200px; background:#f0f0f0;">
<col style="width:100px; text-align:right;">
</colgroup>
<tr>
<td>Product</td>
<td>Sales</td>
</tr>
<tr>
<td>Books</td>
<td>1000</td>
</tr>
<tr>
<td>Pens</td>
<td>500</td>
</tr>
</table>
</body>
</html>
Explanation: By defining <colgroup>
and <col>
elements, you apply styling to entire columns in one place, making it easier to maintain consistent formatting.
Key Takeaways
<colgroup>
and<col>
help group and style columns collectively.- Apply widths, alignment, or background colors to entire columns without repetitive code.
- Use
colgroup
to maintain consistent table structures and styling. - Combining
colgroup
with CSS simplifies table maintenance. - Organized column styling improves clarity and consistency in large tables.