The <th>
HTML element is used to define a header cell in a table. It stands for "table header" and is used within a <tr>
(table row) element to specify a header for a column or row in a table. The <th>
element is typically rendered with bold text and centered alignment by default, providing a clear distinction from regular table data cells (<td>
).
Usage and Characteristics
The <th>
element is used within a <tr>
element, which is part of a <table>
. It can contain text, images, or other inline elements that serve as headings for the data in the corresponding columns or rows. Here is an example of how the <th>
tag can be used:
<table>
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apples</td>
<td>10</td>
<td>$1.00</td>
</tr>
<tr>
<td>Bananas</td>
<td>5</td>
<td>$0.50</td>
</tr>
</tbody>
</table>
Valid Attributes for <th>
Attribute | Description |
---|---|
colspan | Specifies the number of columns a header cell should span. |
rowspan | Specifies the number of rows a header cell should span. |
headers | Specifies one or more header cells that the cell is related to, enhancing accessibility. |
scope | Defines the scope of the header cell. Possible values are col, colgroup, row, and rowgroup, indicating whether the header applies to a column, column group, row, or row group. |
The <th>
element supports all global attributes, allowing for additional customization and interaction through CSS and JavaScript.
Benefits and Considerations
Semantic Meaning: The
<th>
element provides semantic meaning by indicating that the enclosed content is a header for a table column or row, which helps both users and search engines understand the structure of the table.Accessibility: Proper use of the
<th>
element, along with attributes likescope
, enhances accessibility by helping screen readers and other assistive technologies understand the relationships between table headers and data cells.Styling Flexibility: While the default styling uses bold text and centered alignment, the appearance of text within a
<th>
element can be customized using CSS to fit the design of the webpage.
In summary, the <th>
element is a fundamental component for creating tables in HTML, providing a way to define headers for columns or rows. Its attributes allow for flexibility in spanning multiple rows or columns and improving accessibility, making it an essential element for presenting tabular data effectively.