Vertically centring multi-line text with CSS

This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
So you have a fixed height container, and you want your text to be vertically centred, whether it be one line or many lines of text.  In every browser.   This is possible, as I just learned from this article.

For all modern browsers, and IE8 and IE9, the method uses display:table-cell.  For IE6 and IE7, the method described in the above article is used, which takes advantage of a height bug.

You HTML looks like this:

<div id="container">
	<div id="wrapper">
		<div id="content">
			Stuff and things
		</div>
	</div>
</div>

Your CSS looks like this:

#container
{
	width:200px;
	height:50px;
	background-color:red;
	*position:relative;
}
#wrapper
{
	background-color:green;
	height:inherit;
	display:table-cell;
	vertical-align:middle;
	*height:auto;
	*position:absolute;
	*top:50%;
}
#content
{
	background-color:blue;
	*position:relative;
	*top:-50%;
	color:white;
}

The result looks like this:

IE6

ie6-multilineie6-singleline

IE7

ie7-multilineie7-singleline

IE8

ie8-multilineie8-singleline

IE9 Beta

ie9-multilineie9-singleline

Google Chrome

chrome-multilinechrome-singleline

And of course, this is not just constrained to text.  #content can be any variable-height block...

Author

Administrator (1)

comments powered by Disqus