The <th>
tag in HTML is used to define header cells in a table. These cells typically appear at the top of a column or at the beginning of a row and describe the type of data found in the corresponding cells. Using <th>
helps improve table accessibility and readability.
📌 What Is the <th>
Tag?
- Stands for table header.
- Typically placed inside a
<tr>
(table row) element. - Renders text bold and centered by default in most browsers.
- Can be used to create headers for columns, rows, or groups of data.
- Improves semantic meaning and accessibility of tables, as screen readers identify headers and relate them to corresponding data cells.
✅ Basic Syntax
<table>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<td>Apples</td>
<td>$1.00</td>
<td>10</td>
</tr>
</table>
🧩 Attributes of <th>
Attribute | Description |
---|---|
scope | Defines the cells the header relates to (col , row , colgroup , rowgroup ) |
abbr | Provides an abbreviation for the header content (used for accessibility) |
colspan | Number of columns the header cell should span |
rowspan | Number of rows the header cell should span |
🧪 Example 1: Column Headers
<table border="1">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">Occupation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alice</td>
<td>30</td>
<td>Engineer</td>
</tr>
<tr>
<td>Bob</td>
<td>25</td>
<td>Designer</td>
</tr>
</tbody>
</table>
🧪 Example 2: Row Headers
<table border="1">
<thead>
<tr>
<th></th>
<th>Math</th>
<th>Science</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Alice</th>
<td>90</td>
<td>85</td>
</tr>
<tr>
<th scope="row">Bob</th>
<td>80</td>
<td>88</td>
</tr>
</tbody>
</table>
🎨 Styling <th>
By default, browsers render <th>
cells bold and centered. You can customize with CSS:
th {
background-color: #4CAF50;
color: white;
padding: 8px;
text-align: left;
}
⚠️ Accessibility Tips
- Always use the
scope
attribute to clarify header relationships. - Use
<th>
for all headers instead of styling<td>
to look like headers. - Use
abbr
for long headers to provide accessible abbreviations. - Avoid using tables purely for layout; reserve tables for tabular data.
🏁 Summary
The <th>
tag is crucial for defining headers in HTML tables, enhancing structure, semantics, and accessibility. Proper use of <th>
helps both users and assistive technologies understand the table data clearly.