<th> Tag in HTML | Defining Table Headers
The <th> tag in HTML is used to define header cells in a table. By default, text in a <th>
element is bold and centered, making it distinct from regular data cells (<td>
). This tag helps create visually clear and structured tables, enhancing readability and accessibility.
Key Points on <th> Tag:
- Header Cells: The
<th>
element is typically placed within<tr>
(table row) tags to define header cells in rows. - Default Styling: Text within
<th>
tags is bold and centered by default. - Scope Attribute: The
scope
attribute can be added to<th>
to specify whether the header applies to a row, column, or group of rows/columns.
Syntax of <th> Tag:
Syntax Example
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</table>
Example of <th> Tag in HTML:
This example demonstrates the use of the <th>
tag to define headers in a table.
Code Example
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>Alice</td>
<td>24</td>
<td>New York</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
<td>Los Angeles</td>
</tr>
</table>
Output
Name | Age | City |
---|---|---|
Alice | 24 | New York |
Bob | 30 | Los Angeles |
Attributes of <th> Tag:
- Global Attributes: The
<th>
tag supports global attributes likeclass
,id
,style
, andtitle
. - Scope Attribute: The
scope
attribute can be set tocol
,row
,colgroup
, orrowgroup
, specifying the cell's scope.
Advantages of Using <th> Tag:
- Readability: Table headers improve readability by clearly identifying data columns or rows.
- Screen Reader Accessibility: Screen readers recognize
<th>
tags as headers, providing context for visually impaired users. - Styling: Easily style table headers separately from data cells for a professional look.
The <th>
tag is essential for creating accessible and readable tables, allowing easy identification of data columns or rows in HTML tables.