How to Horizontally and Vertically Center a Div

How To Horizontally Center a Div

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

<html>
  <body>
    <h2>This is the page</h2>
    <div class="center"><p>This is the div center</p></div>
  </body>
</html>Code language: HTML, XML (xml)

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; 
}Code language: CSS (css)

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;
}Code language: CSS (css)

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.

Leave a Reply