Centring Pages Without Tables
A common requirement in web design is to centre a page horizontally and vertically within the browser window, such as is the case with the main pages of this site. Centring horizontally is straightforward, but vertical centre is less so.
The following code will centre an object with width and height dimensions of 400px and 200px respectively:
The object can be seen here, centred in a pop-up window.
Deconstruction: explaining the code
The approach is fairly simple. The object is given width and height dimensions and absolute position on the page. The top and left of the object are then set to 50%, which places the top left corner in the centre of the page, and it will remain so when the page is resized. Finally, the top and left margins are set to negative values of 50% of the height and width respectively.
Limitations
The obvious drawback to this method is that it requires a fixed height and width for the page. If you need a fluid layout, then it will not work. But if you can live with a fixed dimensional layout, it's fine.
It works in most tested browsers, one exception being Internet Explorer for Macintosh when a DOCTYPE is declared for the page. If no DOCTYPE is declared, the solution also works in that browser (test). Given that a lack of DOCTYPE can cause its own problems, and that Microsoft has long since abandoned development of the Macintosh version of Internet Explorer, I prefer to use a JavaScript to accommodate it. The JavaScript causes the page to ‘jump’, as the centred element is repositioned after the page has loaded, but it's a compromise that I'm willing to accept to balance design against backwards compatibility.
Another solution to the problem, by Joe Gillespie, is also available. His approach is slightly more complicated than the code presented here, in that it relies on a horizontally centred object being placed within another that's centred vertically. Again, the solution fails in Internet Explorer for Macintosh if a DOCTYPE is declared for the page.