How to center a div?

ยท

2 min read

In this blog, we are going to see some ways through which we can center our div. As according to me the centering of div is a very crucial part of CSS. Till now, in all the projects I have made, at some point, I always get confused about this. So, let's explore some ways to make it happen๐Ÿ˜€


First, let's get some info about a div. So,

What is a div?๐Ÿค”

We can consider a div as a container in which you can store any element you wish.

\=> It's a block element. (Huh!) now, what the heck is this block element mean?

Block element: An element that takes the whole width available is known as a block element.

<div id="myDiv">
    <p>This is a paragraph</p>
</div>

 body{
            background-color: gray;
        }
        #myDiv{
            border: 2px solid;
            width: 50vw;
            height: 50vh;
            font-size: 3rem;
            background-color: antiquewhite;
        }

I have given it some styling so you can easily identify the div.(The spaces on the right and left of the div are due to default CSS margin and padding)

So, you are saying that it takes the whole width so how we can center it at all?

For centering the div we first need to give it a certain width.

Let's say I gave it a width of 50 vw.

Now, you can see that the div lies on the left side of the screen.

How we can center it now?

We can see here now that the div still takes the whole width with a small difference that now the element is of width 50vw and the rest is taken as its margin.

How we can solve it though?๐Ÿ™„

\=>We can do this by dividing the margin equally on both the left and right side of the element.

Wait! you are saying that I have to now measure how much it should take to be equal on both sides. Well, the answer is NO!

You can easily do this by adding a property of CSS known as margin: auto

How is it a kind of magic?

CSS auto just divides the margin into equal parts on both of sides of the element.

First, try it yourself.

 body{
            background-color: gray;
        }
        #myDiv{
            border: 2px solid;
            width: 50vw;
            height: 50vh;
            font-size: 3rem;
            background-color: antiquewhite;
            margin: auto; /*The magic is here*/
        }

See, this divided the margin equally.


Thank you for reading

ย