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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s