The HTML <caption>
element represents the title of a table and must be the first child of a <table>
element. A caption can introduce context for a table, making it easier to understand at a glance as well as aid in accessibility.
Syntax
The syntax for the <caption>
element is as follows (notice the positioning before the <thead>
element, and immediately after the opening <table>
tag):
1 |
<table>
|
2 |
<caption>Table Caption</caption> |
3 |
<thead>
|
4 |
<tr>
|
5 |
<th>Header 1</th> |
6 |
<th>Header 2</th> |
7 |
<th>Header 3</th> |
8 |
</tr>
|
9 |
</thead>
|
10 |
<tbody>
|
11 |
<tr>
|
12 |
<td>Row 1, Column 1</td> |
13 |
<td>Row 1, Column 2</td> |
14 |
<td>Row 1, Column 3</td> |
15 |
</tr>
|
16 |
<tr>
|
17 |
<td>Row 2, Column 1</td> |
18 |
<td>Row 2, Column 2</td> |
19 |
<td>Row 2, Column 3</td> |
20 |
</tr>
|
21 |
</tbody>
|
22 |
</table>
|
Example
Suppose you are building a website for a small restaurant and want to display a menu on your website.
You choose a <table>
to organize the different menu items into categories called Appetizers, Entrees, and Desserts. You also want to include a brief description of the menu items in each category.
You could use the <caption>
element to give an overall title to the table, then provide a brief summary of what each category contains and come up with something like the following example:
Attributes
The <caption>
element supports Global Attributes in HTML and has no specific attributes. A <caption>
element’s end tag can be omitted if the caption element is not immediately followed by ASCII whitespace or a comment.
Content
The content of the <caption>
element would be a short, descriptive text that identifies the content of the table. It’s useful for getting quick context of what data resides in the table.
Did You Know?
- The
<caption>
element should only be used once per<table>
element. - The placement of the
<caption>
element is important. It should structurally be placed before the<thead>
element to ensure that it is announced before the table content. - The
<caption>
element is often used for accessibility purposes, as it provides a way to describe the content of a table for users who may not be able to see the table visually.