How To Horizontally Center a Div

13th February 2019   Programming

You might have encounter something like a portion of your website is not being centered, you were sure that there was no problem with your code but still it won’t go center. We’re here to help you!

In this article we’ll be giving you tips and tricks on how to center your div using CSS horizontally and/or vertically.


Basic HTML code

Let’s use this basic html code for this tutorial, let’s say you only have one div tag with a class name center

    <h2>This is the page</h2>
    <div class="center"><p>This is the div center</p></div>

Centering a Div in a Page

Make a <head> tag above the <body> tag and inside the head tag copy the following CSS code.

.center {
     margin: 0 auto;
     width: 250px; 

The code above will give your div a zero margin vertically and an auto adjust margin horizontally, that means both left and right margins will have the same value and that’ll make the div go center horizontally.

Centering a Div Horizontally & Vertically

Replace your previous code with the following code if you want to center your div horizontally and vertically.

.center {
     position: absolute;
     width: 250px;
     height: 250px;
     margin: auto;
     top: 0;
     right: 0;
     bottom: 0;
     left: 0;

The code above will set your element’s position absolute, give it a width and height, an auto adjust margin for both horizontal and vertical, and a transform position of zero (top, right, bottom and left).

That way, your div will be displayed at the center of the page.

Sample output based on the code provided above.
React to this topic
Bernard Polidario
About Bernard Polidario

A full-stack developer who has been around programming community for 10+ years and still has a lot of passion for programming and design. I am the founder of WeeklyHow and I can be reached at [email protected]

Leave a Reply

Your email address will not be published. Required fields are marked *