Wednesday, 28 January 2009

Position a DIV Horizontally and Vertically Using CSS.

Currently missing from CSS is the ability to position an element so that it is centred on the page, both horizontally and verticalally. But fear not, this effect is very simple to achieve.

This has been tested in IE7, Firefox3 and Safari3 and all work fine. (It may work in other browsers I just haven't tested it)

The idea is quite straight forward:

  • We build a standard horizontal layout, using text-align:center (for IE) and a wrapper div with margin:0 auto.

  • Then we add a div above the wrapper with height:50% and an top negative offset position of half the height of the wrapper div.


The wrapper will then be centred horizontally and vertically.

<html>
<head>
<style>

html, body {
margin: 0;
padding: 0;
text-align: center;
}

#layoutspacer {
position: relative;
margin-top: -100px; /* Half height of layoutwrapper */
height: 50%;
width: 100%;
}

#layoutwrapper {
background: yellow;
position: relative;
margin: 0 auto;
height: 200px; /* Adjust as appropriate */
width: 200px; /* Adjust as appropriate */
overflow: hidden;
}

</style>
</head>
<body>

<div id="layoutspacer"></div>
<div id="layoutwrapper">
Enter content here
</div>

</body>
</html>

...Centred...

Update: This solution only works in quirks mode, for a better solution see here

1 comment:

robert said...

the problem will appear when the screen resolution is smaller than a div. the right left corner is going to desappear - the smaller the screen the more div is going to desappear. :(