Centre Vertical

Unfortunately none of the current browsers support setting margins to auto for vertical centring. All is not lost however for we can align our content to the centre of the page vertically using stylesheet commands.

For all browsers except Internet Explorer we can define a table with height 100% and centre align the content of a cell within the table. Internet Explorer doesn't yet support the display types of table. and table-cell but IE7 and earlier do support negative positioning (which the other browsers don't support). We can therefore align the top of our content to the centre of the browser window and then offset it upward by 50% of its height to achieve the same final result.

Here is the stylesheet commands required to vertically align to the centre of the page:

<style type="text/css">
body, html {height: 100%;}
#tbl[id] {display: table; height: 100%;}
#cell[id] {display: table-cell; vertical-align: middle;}
<!--[if lte IE 7]><style type="text/css">
#tbl {position: absolute; top: 50%;}
#cell {position: relative; top: -50%;}

It is now a simple matter to enclose all of the content of the page within two div tags like this:

<div id="tbl"><div id="cell">
our centred vertical web page content goes here

This sample page shows you what some full page vertically centred text looks like in your browser.

Of course you may not want to centre in the whole window. You may just need to centre it within another div of known height. All you need to change in order to do this is to replace the top line of the stylesheet code with one that refers to the div you want to align it in instead. For example if the div you want to align within has id="blk" and it is 300 pixels high then we can vertically centre align its contents if we replace the top line with:

#blk {position: relative; height: 300px;}

Of course this line will probably already exist in order to define the height of the div to start with.

This sample page shows you what some vertically centred text in a 300 pixel high div looks like in your browser.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow