HTML <thead> Tag
The HTML <thead>
tag is used to group the header content in an HTML table. It is typically used alongside <tbody>
and <tfoot>
to structure the table into logical sections, enhancing its readability and semantic meaning. The <thead>
tag contains rows (<tr>
) and header cells (<th>
) that describe the table’s columns.
By organizing table headers in the <thead>
tag, you improve accessibility and make it easier for screen readers and scripts to interpret the table’s structure.
Basic Syntax of HTML <thead> Tag
The basic structure of a table with a <thead>
section is:
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</tbody>
</table>
The <thead>
section contains rows with header cells that describe the columns of the table.
Example of a Table with <thead>
Here’s an example of a table that organizes student scores with a header section:
index.html
<!DOCTYPE html>
<html>
<body>
<h2>Student Scores</h2>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Subject</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alice</td>
<td>Math</td>
<td>90</td>
</tr>
<tr>
<td>Bob</td>
<td>Science</td>
<td>85</td>
</tr>
</tbody>
</table>
</body>
</html>
Explanation: The <thead>
section contains the headers for the “Name,” “Subject,” and “Score” columns, while the data resides in the <tbody>
section.
Styling the <thead> Section with CSS
The <thead>
section can be styled independently to differentiate it from the rest of the table:
index.html
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
thead th {
background-color: #f4f4f4;
font-weight: bold;
text-align: center;
}
</style>
</head>
<body>
<h2>Styled Table Headers</h2>
<table>
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Laptop</td>
<td>10</td>
<td>$1000</td>
</tr>
<tr>
<td>Phone</td>
<td>20</td>
<td>$500</td>
</tr>
</tbody>
</table>
</body>
</html>
Result: The header cells are styled with a light background and bold text to differentiate them from the table body.
Attributes of HTML <thead> Tag
- Global Attributes: Supports all global attributes, such as
id
,class
, andstyle
. - Event Attributes: Allows event handlers like
onclick
,onmouseover
, andonfocus
.
Practical Applications of the <thead> Tag
- Table Headers: Organize column headers for easy readability and semantic clarity.
- Styling: Apply distinct styles to headers using CSS to improve visual presentation.
- Accessibility: Enhance table navigation for screen readers by clearly separating header content.
- Responsive Tables: Use the
<thead>
tag to dynamically adjust header styles for mobile or smaller screens.