The Wayback Machine - https://web.archive.org/web/20250114231614/https://www.geeksforgeeks.org/how-to-horizontally-center-a-div-using-css/
Open In App

How to horizontally center a div using CSS ?

Last Updated : 14 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Dive deep into the world of JavaScript with our JavaScript Full Course Online, offering everything from the basics to advanced techniques. Learn how to build interactive websites, optimize your code, and earn a certification to showcase your skills.

Take the Three 90 Challenge! Complete 90% of the course in 90 days, and earn a 90% refund. Push your limits and stay motivated as you work towards mastering JavaScript. Join now and get started on your JavaScript learning journey!


Next Article

Similar Reads

three90RightbarBannerImg