Tag: web design

How to center a DIV both vertically and horizontally

How to center a DIV both vertically and horizontally

This quick and lightweight method offers the benefit of getting the job done in just a few lines of CSS, in those situations where using a framework / boilerplate would be an absolute overkill, i.e. a simple separate standalone login screen for an already existing application, where the actual login form would look just lovely in the middle of the screen. The only rather insignificant downside of this technique is that the size of the centered element is fixed.

body {position:relative}
#centered {position:fixed; top:50%; left:50%;}
#centered {width:18em; height:8em; margin-top:-4em; margin-left:-9em}

We basically just set relative positioning on the body and fixed or absolute positioning on the div element to be aligned. Define the div dimensions in em units and set the top and left attributes to 50%. Set the margin-top and margin-left attributes to minus half the width and height values.