HTML <caption> Caption tag
The <caption>
tag in HTML is used to provide a caption or a title for a table. It is a child element of the <table>
tag and is used to describe the content or purpose of the table. The caption is typically displayed above or below the table, depending on the browser's default rendering and CSS styles.
Syntax:
<table>
<caption>Table Caption</caption>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</tbody>
</table>
Key Characteristics:
Semantic Meaning: The
<caption>
tag provides a semantic way to describe the purpose or content of the table, enhancing the accessibility and usability of the table for users and assistive technologies.Placement: By default, the caption is displayed above the table. However, this can be changed using CSS if needed.
Visibility: Captions are visible and help users understand the context or purpose of the table. They are also useful for screen readers, improving the accessibility of the table content.
Example:
<table>
<caption>Annual Sales Report</caption>
<thead>
<tr>
<th>Year</th>
<th>Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>2023</td>
<td>$50,000</td>
</tr>
<tr>
<td>2024</td>
<td>$60,000</td>
</tr>
</tbody>
</table>
In this example:
- The
<caption>
tag is used to provide a descriptive title "Annual Sales Report" for the table, helping users understand what the table represents.
CSS Styling:
You can use CSS to style the <caption>
tag, such as changing its position, font size, or color.
Example CSS:
<style>
table {
width: 100%;
border-collapse: collapse;
}
caption {
font-size: 1.5em;
text-align: center;
margin-bottom: 10px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
</style>
In this CSS example:
font-size
changes the size of the caption text.text-align
centers the caption above the table.margin-bottom
adds space between the caption and the table content.
Accessibility and SEO:
- Accessibility: The
<caption>
tag improves accessibility by providing context for users of screen readers. It helps convey the purpose of the table to users who may not be able to interpret the table’s content visually. - SEO: While the
<caption>
tag itself does not directly impact SEO, providing clear and descriptive captions can enhance the user experience and potentially improve engagement with the content.