How to position div to center of webpage using CSS

In this post, I am going to show you a very common problem where people get stuck. It is very easy to align most of the elements to the center using text-align in CSS. But if you are working with div element it is not that easy as it looks like. text-align will bring all the text and most of the elements to the center. But here it will not work.  So here I will explain with the example of Position div to center of webpage using CSS.

Bottom Sticky Music Player Source Code in JavaScript and CSS

Simple Static Layout Page Using HTML and CSS

Position div to center of webpage using CSS

The below CSS will make a div center positioned

margin:0 auto;

To make you a better understand I am going to give you an easy example.

Let’s assume we have a div with id main. And we want this div to be in the centered position.

<!DOCTYPE html>
<html>
<head>
  <title>Div to the center</title>
  <style type="text/css">
    #main{
      width: 600px;
      height: 400px;
      background-color: lavender;
      margin:0 auto;
    }
  </style>
</head>
<body>
  <div id="main">
  </div>
</body>
</html>

Now, the above code will bring the div to the center.

Bounce a circle inside HTML5 canvas infinitely



background-color can be anything you like. I just used it show you that it is working otherwise the default color would be white and you can not distinguish between the body and the div.

 What does margin:0 auto means?

So its a very good question if you don’t know margin:0 auto meaning.

Well, we gonna sort it out. Here you can see two parameters. One is 0 (zero) and another one is auto.

Zero means it will give you the element a margin of 0 for both the top and bottom. In simple word, It is nothing but

margin-top: 0;
margin-bottom: 0;

Create CSS Bounce Effect with CSS3 Animation

And the second parameter is for the margin for left and right. Here it is set to auto because we want to let the browser determine how much margin should be there to get the equal margin from both the right and left.

In simple words,

margin-left:auto;
margin-right:auto;

Thus we can achieve centering the div by using margin:0 auto

margin:0 auto is equivalent to :

margin-top: 0;
margin-bottom: 0;
margin-left:auto;
margin-right:auto;

Leave a Reply

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