How to center a table in CSS

Designing a website involves an engaging process when incorporating tables. Typically, tables are aligned to the left by default; however, with CSS margin property adjustments, we can center-align them.

If we specify the value of margin-left and margin-right as auto, the web browsers will display the table in the center. An alternative approach is to employ the margin shorthand property with auto value to horizontally align the table instead of individually setting margin-left and margin-right properties.

Instead of aligning the table to the center, the text-align: center; CSS property solely centers the content within the table, like the text enclosed in the table cells.

Let's understand this by using an illustration.

Example

In this instance, we employ the text-align: center; attribute to centrally align the content within the table, while utilizing margin-left: auto; and margin-right: auto; to centrally position the table.

Example

<!DOCTYPE>

<html>  

<head>

<style>  

table, th, td {  

border: 1px solid black;

margin-left: auto;

margin-right: auto;

border-collapse: collapse;  

width: 500px;

text-align: center;

font-size: 20px;

}  

</style>  

</head>

<body>  

<table>  

<tr>

<th>First_Name</th>

<th>Last_Name</th>

<th>Subject</th>

<th>Marks</th>

</tr>  

<tr>

<td>James</td><td>Gosling</td><td>Maths</td><td>92</td>

</tr>  

<tr>

<td>Alan</td><td>Rickman</td><td>Maths</td><td>89</td>

</tr>  

<tr>

<td>Sam</td><td>Mendes</td><td>Maths</td><td>82</td>

</tr>  

</table>  

</body>

</html>

Output

Input Required

This code uses input(). Please provide values below: