Rasik Rasik - 2 years ago 62
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:


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


<div class="vcenter">


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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download