Thursday, 2 April 2009

Position an Element Horizontally and Vertically Using CSS. (Take 2)

Positioning an element so that it is centred on the page, both horizontally and verticalally, is very simple to achieve. We do need to know the width of the element, so this does need to be fixed.

It has been tested in IE7, Firefox3 and Safari3 and all work fine. (It may work in other browsers I just haven't tested it)
This idea expands our first idea as this only worked in quirks mode. This second solution uses the xhtml transitional doctype.

The idea is quite straight forward, we position the element so the top left corner is in the middle of the page. Then we adjust the top and left margins so the centre of the element is in the middle of the page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

* {
margin: 0;
padding: 0;

#layoutwrapper {
height: 200px; /* Adjust as appropriate */
width: 550px; /* Adjust as appropriate */
margin-left: -275px; /* (Width/2)*-1 */
margin-top: -100px; /* (Height/2)*-1 */
left: 50%;
top: 50%;
overflow: hidden;
position: absolute;
background: yellow;


<div id="layoutwrapper">
Enter content here


...Centred with doctype...

No comments: