How do we include a table caption in HTML?

The <caption> element is used to add caption to an HTML table. A "caption" must be the first descendant of a parent "table" in an HTML document, however it can be visually positioned at the bottom of the table using CSS.


<caption>Table title...</caption>

The <caption> element contains global attributes and deprecated align attributes (left, right, top, bottom). This element must be used immediately after the table tag is opened as it is a table caption. If a figure needs to be captioned instead of a table use <figcaption>.

Following are the examples…


In the following example we are adding the caption to the table by default aligned to the center.

<!DOCTYPE html> <html> <style> table, th, td { border: 1px solid black; } </style> <body> <table> <caption>STUDENTS</caption> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>siddarth</td> <td>Roy</td> <td>21</td> </tr> <tr> <td>Arjun</td> <td>Reddy</td> <td>22</td> </tr> <tr> <td>Sing</td> <td>Roy</td> <td>23</td> </tr> </table> </body> </html>


On executing the above script, it will create the table and the text "student" on top of the table, as we mentioned in between the <caption> tag.

Example: Using JavaScript

Now, let us see an example of this using JavaScript −

<!DOCTYPE html> <html> <body> <table id="myTable" border="1"> <tr> <th>Firstname</th> <th>Lastname</th> </tr> <tr> <td>Siddarth</td> <td>Roy</td> </tr> <tr> <td>Arjun</td> <td>Reddy</td> </tr> </table> <form> <input type="button" onclick="caption()" value="Click"> </form> </body> <script type="text/javascript"> function caption(){ var x=document.getElementById('myTable').createCaption() x.innerHTML="<b>STUDENTS</b>" } </script> </html>


When the script is executed, it will create a table along with the click button. When the click button is pressed, the caption gets triggered and displays the text "students" on top of the table.