How to center a table in CSS - CSS Tutorial

How to center a table in CSS

BLUF: Styling is what brings the web to life, and mastering How to center a table in CSS is key to creating beautiful, responsive interfaces. This tutorial breaks down the concepts and syntax you need to succeed with CSS.
Visual Design Hack: How to center a table in CSS

CSS is all about presentation. Discover how How to center a table in CSS works to transform plain HTML into a premium user experience in the guide below.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience