html

How to Center a Table in HTML?

In HTML, a table plays an important role in organizing data. The table uses a combination of rows and columns to store data. It allows the developer to arrange the pile of unorganized data in rows and columns.

In HTML, <table> tag is used for the creation of a table. Inside this tag <tr> and <td> tags are used to create the rows and columns of a table. HTML allows us to format the table with the help of CSS properties. In this post, we have demonstrated the way to center a table in HTML.

How to Center a Table in HTML?

In HTML, tables are primarily used to enhance the readability and aesthetics of the content. The following practical example showcases the process of a table creation along with the process of keeping it in center.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <title>First Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div>
        <h1 style="text-align:center;">Simple Table</h1>
        <table style="margin-left:auto; margin-right:auto; text-align:center;"
border="1">
            <tr>
                <th>Names</th>
                <th>Grades</th>
            </tr>
            <tr>
                <td>Alice</td>
                <td>A</td>
            </tr>
            <tr>
                <td>Jhon</td>
                <td>C</td>
            </tr>
            <tr>
                <td>Alex</td>
                <td>B</td>
            </tr>
        </table>
    </div>
</body>
</html>

In this code, we have created a simple table with the help of <table>, <tr>, and <td> tags. Inside the <table> tag, three CSS properties are used. The value for both margin-left and margin-right is auto while the value of text-align is set to center.

Output

The output clearly shows that the table is successfully centered with the help of CSS margin properties.

That’s it! You have learned to center the table with the help of CSS properties.

Conclusion

In HTML, we can center the table by applying CSS margin-left, margin-right properties and set their values as auto. This will add the margin on the left and right side of the table equally which will align the table at the center of the HTML page. Additionally, you can use the text-align property to centralize the content of the table. All these properties are applied on an HTML code to center a table in HTML.

About the author

Adnan Shabbir