Introduction
The ‘<colgroup>
‘ element in HTML is used to group a set of ‘<col>
‘ elements that collectively define the properties for columns within a table.
It provides a way to apply common styling or attributes to multiple columns, making the code more concise and maintainable. The ‘<colgroup>
‘ element is often placed as a child of the ‘<table>
‘ element.
Here is an example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table with Col Element</title>
<style>
/* Apply styles to the first column */
col:first-child {
background-color: #f2f2f2;
}
/* Apply styles to the second column */
col:nth-child(2) {
background-color: #e0e0e0;
}
/* Apply styles to the third column */
col:nth-child(3) {
background-color: #d2d2d2;
}
/* Apply common styles to all columns */
col {
padding: 10px;
text-align: center;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<table border="1">
<colgroup>
<col> <!-- First Column -->
<col> <!-- Second Column -->
<col> <!-- Third Column -->
</colgroup>
<tr>
<td>Row 1, Col 1</td>
<td>Row 1, Col 2</td>
<td>Row 1, Col 3</td>
</tr>
<tr>
<td>Row 2, Col 1</td>
<td>Row 2, Col 2</td>
<td>Row 2, Col 3</td>
</tr>
</table>
</body>
</html>
Output :
This usage of ‘<colgroup>
‘ can make the HTML code cleaner and more organized, especially when dealing with large tables where column styling or attributes need to be applied consistently.