How to Add Caption to Table in HTML: Simple Guide
To add a caption to a table in HTML, use the
<caption> tag immediately inside the <table> element. The caption text appears above the table by default and describes the table's content.Syntax
The <caption> tag is placed directly inside the <table> element, usually as the first child. It holds the text that describes the table.
- <table>: The container for the table data.
- <caption>: The element that adds a title or description to the table.
html
<table> <caption>Table Caption Here</caption> <!-- table rows and cells go here --> </table>
Example
This example shows a simple table with a caption describing its content. The caption appears above the table.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Table Caption Example</title> <style> table { border-collapse: collapse; width: 50%; margin: 20px auto; font-family: Arial, sans-serif; } caption { font-weight: bold; font-size: 1.2rem; margin-bottom: 8px; } th, td { border: 1px solid #333; padding: 8px; text-align: left; } </style> </head> <body> <table> <caption>Monthly Sales Data</caption> <thead> <tr> <th>Month</th> <th>Sales</th> </tr> </thead> <tbody> <tr> <td>January</td> <td>$1000</td> </tr> <tr> <td>February</td> <td>$1200</td> </tr> </tbody> </table> </body> </html>
Output
A centered table with a bold caption above it reading 'Monthly Sales Data'. The table has two columns labeled 'Month' and 'Sales' with two rows of data for January and February.
Common Pitfalls
Common mistakes when adding captions to tables include:
- Placing the
<caption>tag outside the<table>element, which will not work. - Using other tags like
<th>or<div>for captions, which is semantically incorrect. - Not styling the caption, making it hard to distinguish from table data.
html
<!-- Wrong way: caption outside table --> <div>Monthly Sales Data</div> <table> <tr><td>Data</td></tr> </table> <!-- Right way: caption inside table --> <table> <caption>Monthly Sales Data</caption> <tr><td>Data</td></tr> </table>
Quick Reference
| Element | Purpose | Placement | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|