Rasik Rasik - 7 months ago 10
HTML Question

How to centre a div vertically?

I have a div that I want to position at the center of a page(both vertically and horizontally).

For centring it horizontally I used the center tags around the div and for vertically centring it is tried a couple of things but none of them actually working.

Check out the code:

CSS:

.vcenter{
height: 50px;
width: 50px;
background: red;
vertical-align: middle;
margin-top: calc(50% - 25px);
}


HTML :

<center>
<div class="vcenter">

</div>
<center>


Also I don't think using centre tags around the the div to centre an object is the best way to so it.

What I want to know is


  • How can I centre the div both vertically and horizontally no matter what the size of the screen is ?

  • Is there a better way to centre the div horizontally rather than using the center tags ?


Answer

If available, using flex is the easiest. Apply these styles to the container in which you want to center your div:

display: flex;
align-items: center;
justify-content: center;