How to create a table with a caption?


We use the <caption> tag, to create a table with caption in HTML. The caption tag will be inserted immediately after the <table> tag. We can add only one caption for one table. By default, the alignment of this tag is center. We can change the alignment using CSS property called align.

Syntax

Following is the syntax of the caption tag of HTML

<caption>Caption of the table...</caption>

Example 1

In the following example we are creating a table with employee name and employee id with Employees as the caption.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> table, tr, th, td { border: 1px solid black; } </style> </head> <body> <table> <caption>Employees</caption> <tr> <th>EmployeeName</th> <th>EmployeeId</th> </tr> <tr> <td>Yadav</td> <td>022</td> </tr> <tr> <td>Abdul</td> <td>025</td> </tr> <tr> <td>Jason</td> <td>208</td> </tr> </table> </body> </html>

The align property

We can change the alignment using CSS property the align property. Following is the syntax for this −

<caption style="text-align:value" >Caption of the table...</caption>

Example 2

In the example given below we are aligning the we are aligning the caption to the left side of the page −

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> table,tr,th,td { border:1px solid black; } </style> </head> <body> <table> <caption style="text-align: left">Employees</caption> <tr> <th>EmployeeName</th> <th>EmployeeId</th> </tr> <tr> <td>Yadav</td> <td>022</td> </tr> <tr> <td>Abdul</td> <td>025</td> </tr> <tr> <td>Jason</td> <td>208</td> </tr> </table> </body> </html>

Example 3

Let us see another example to create a caption −

<!DOCTYPE html> <html> <head> <style> table, td, th { border: 1px solid black; } </style> </head> <body> <table> <caption>Authors</caption> <tr> <th>JavaFX</th> <th>Krishna</th> </tr> <tr> <td>Scala</td> <td>Satish</td> </tr> </table> </body> </html>

Advertisements