Introduction
The ‘<col>
‘ HTML element defines a column within a table and is used for defining common semantics on all common cells. It is generally found within a ‘<colgroup>‘ element.
‘<col>
‘ allows styling columns using CSS, but only a few properties will have an effect on the column.
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 :

Uses of <col> tag :
Here are some uses of <col> tag :
1. Applying Styles to Columns : You can use the ‘<col>
‘ element to apply specific styles, such as background colors, borders, or text alignment, to individual columns or groups of columns.
<table>
<colgroup>
<col style="background-color: #f2f2f2;">
<col style="text-align: center;">
</colgroup>
<tr>
<td>Column 1</td>
<td>Column 2</td>
</tr>
</table>
2. Setting Column Widths : You can use the width
attribute to specify the width of a column. This is useful when you want to control the width of specific columns in the table.
<table>
<colgroup>
<col width="100px">
<col width="150px">
</colgroup>
<tr>
<td>Column 1</td>
<td>Column 2</td>
</tr>
</table>
3. Spanning Columns : The ‘<col>
‘ element can also be used to define columns that span multiple columns. This is done using the span
attribute.
<table>
<colgroup>
<col span="2">
<col>
</colgroup>
<tr>
<td colspan="2">Spanning Columns 1 and 2</td>
<td>Column 3</td>
</tr>
</table>
4. Defining Column Attributes: You can use the ‘<col>
‘ element to define various attributes for columns, such as class
or id
, making it easier to select and style specific columns with CSS or JavaScript.
<table>
<colgroup>
<col class="highlight-column">
<col>
</colgroup>
<tr>
<td>Highlighted Column</td>
<td>Regular Column</td>
</tr>
</table>
By using the ‘<col>
‘ element along with the ‘<colgroup>
‘, you can enhance the structure and styling of your HTML tables, making them more flexible and maintainable.