To create a table header in HTML, you use the <th>
tag. This tag defines a header cell within an HTML table. Table headers are typically displayed in bold and are used to label the columns of data.
Understanding Table Structure
Before diving into the specifics of the <th>
tag, it's important to understand the basic structure of an HTML table:
<table>
: This is the main container element for your entire table.<tr>
: Defines a table row.<th>
: Defines a header cell within a row, typically used in the first row to label the columns.<td>
: Defines a standard data cell within a row.
Using the <th>
Tag
The <th>
tag is crucial for creating well-structured and accessible tables. According to the provided reference, an HTML table includes two types of cells:
- Header cells: Contain header information and are created using the
<th>
element. - Data cells: Contain the data and are created using the
<td>
element.
Here's how to use the <th>
tag to create a table header:
-
Start with the
<table>
element: Begin by creating your main table container using<table>
tag. -
Add a table row
<tr>
: Inside the<table>
, begin a new row with the<tr>
tag. This row will contain your headers. -
Use the
<th>
tags: Place one or more<th>
tags inside the<tr>
tag. Each<th>
tag defines a table header cell. -
Add data rows: Create additional rows using
<tr>
with<td>
elements to add data to the table.
Example
Here's a practical example of how to create a simple table header:
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Occupation</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
<td>Engineer</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>25</td>
<td>Doctor</td>
</tr>
</table>
In this example, the first row uses <th>
tags to define the headers: "Name", "Age", and "Occupation". The subsequent rows use <td>
tags to define the table data for each respective column.
Key takeaways
- The
<th>
tag is used to create a header cell in HTML tables. - Header cells typically label the columns of data in a table.
- Use the
<th>
tag within<tr>
tags in the first row of the table. - Always use
<td>
tags to add the table data under the headers.
By correctly using the <th>
tag, you can create accessible and well-organized HTML tables.