Make a div center of viewport – Horizontally and vertically [duplicate]

#wrapper
{
 width:500px;
 height:500px;
 margin:0 auto;
 background:#f7f7f7;
 position:absolute;
 left:50%;
 top:50%;
 margin-left:-250px;
 margin-top:-250px;
}

Demo: http://jsfiddle.net/fJtNQ/

Why is this working?

Well, basically you have an absolute positioned element inside the dom. It means that you can position it wherever you want and if you don’t have a relative positioned element as parent, left and top will be the distance from the document’s left/top origin.

Assigning left:50% and top:50% enables this element to be positioned always in the center of the screen, but in the center you will find the top left corner of the element.

If you have fixed width/height, you can easily ‘translate’ the point in the center to be actually the center of the wrapper div by giving negative margin-left and margin-top (therefore with the help of some extremely easy basic math their values will be -(width/2) and -(height/2))

EDIT

You can also easily center by using flexbox, plus (a big one) you don’t need to specify w/h, i.e.:

body { /* can also be whatever container */
  display: -webkit-flex;
  display: flex;
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;
}

#wrapper {
  /* whatever style u want */
}

demo: https://jsfiddle.net/00utf52o/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)