To add a title or caption to a table in HTML, you use the <caption>
tag.
Adding a title to your HTML table makes it more accessible and helps users understand the table's content at a glance. The <caption tag defines a table caption>
. This is the standard and recommended way to provide a descriptive title for your tabular data.
Using the <caption>
Tag
The <caption>
tag is specifically designed for table captions. According to the HTML standard, the <caption>
tag <must be inserted immediately after the <table> tag>
.
Here's a simple structure showing where the <caption>
tag goes:
<table>
<caption>Your Table Title Here</caption>
<thead>
... table header content ...
</thead>
<tbody>
... table body content ...
</tbody>
</table>
Placing the <caption>
right after the opening <table>
tag ensures it is correctly associated with the table and renders properly.
Example HTML Table with a Title
Let's look at a practical example:
<!DOCTYPE html>
<html>
<head>
<title>Table with Caption Example</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
caption {
padding: 10px;
caption-side: top; /* Default is usually top, but can be changed */
}
</style>
</head>
<body>
<h2>Sample Data Table</h2>
<table>
<caption>Monthly Sales Report - Q1</caption>
<thead>
<tr>
<th>Month</th>
<th>Sales</th>
<th>Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$5,000</td>
<td>$1,500</td>
</tr>
<tr>
<td>February</td>
<td>$6,200</td>
<td>$2,000</td>
</tr>
<tr>
<td>March</td>
<td>$5,800</td>
<td>$1,800</td>
</tr>
</tbody>
</table>
</body>
</html>
In this example, "Monthly Sales Report - Q1" serves as the title for the table, clearly indicating the data it contains.
Caption Placement and Styling
By default, a table caption will typically be center-aligned above a table
. However, you have control over its appearance using CSS (Cascading Style Sheets).
The reference mentions two key CSS properties for styling the <caption>
:
text-align
: Used to control the horizontal alignment of the caption text (e.g.,left
,right
,center
).caption-side
: Used to specify the placement of the caption relative to the table. Common values includetop
(above the table) andbottom
(below the table).
Here's how you might use CSS to style the caption:
caption {
text-align: left; /* Align caption text to the left */
caption-side: bottom; /* Place caption below the table */
font-weight: bold;
padding: 8px;
}
Using CSS allows you to customize the appearance and position of the table title beyond the default settings, enhancing the visual presentation of your data tables.
Using the <caption>
tag is the semantic and correct way to add a title to your HTML tables, improving both usability and accessibility.