Open In App

How to horizontally center a div using CSS ?

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To make an HTML div center horizontally using CSS is quite easy. We can horizontally center any element using the below-mentioned approaches.

Before centering a div horizontally we need to create a fixed-size div. We have given a border to the div so the centering of that div can be visible. Set the main container width to 100% so the div can be moved around into that container.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Centerin div Horizontally in CSS</title>
    <style>
        div { 
            width: 300px; 
            border: 2px solid black;
        } 
    </style>
</head>

<body>
    <article class="container">
        <div>
            <h1>Geeksforgeeks</h1>
            <p>Horizontally Center Div</p>
        </div>
    </article>

</body>

</html>

Centering div with margin auto Property

This approach lets the browser calculate the available space and place the div in the center horizontally. In thise scenario you have to keep the div width less than the viewport width.

Example:

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Centerin div Horizontally in CSS</title>
    <style>
        div { 
            width: 300px; 
            margin: auto; 
            border: 2px solid black; 
        } 
    </style>
</head>

<body>
    <article class="container">
        <div>
            <h1>Geeksforgeeks</h1>
            <p>Horizontally Center Div</p>
        </div>
    </article>

</body>

</html>

Output:

Horizontlly-center-div

Centering div with margin auto Output


Explanation:

In this example we utilized the browser capability by using the CSS margin property, we set the margin value to auto so the browser can adjust with the available space and place the div into the center of the viewport.

Note: For Microsoft Edge & Internet Explorer, The auto value is not supported in quirks mode.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads