Do not forget display:table-cell

"

The last <table>-based website that I did was tomswebplaces.com, which I believe was in 2003. A lot has changed since, both on the web and the way I write HTML. But today I remembered <table> usage once again; that is, using <table> for layout and design, rather than tabular data.

The task at hand: to align text vertically in a div. At first quite trivial — div inside div, first position:relative, second position:absolute — until it comes to text wrapping. When text wraps to the next line, there's more white space above the box than below. I could not believe that there isn't a native solution for this. Few google queries revealed long forgotten display:table-cell, combined with vertical-align:middle achieves desired behavior. It works perfectly on all standard compliant browsers; however, IE6 and IE7 that do not support display:table-cell.

Below is the way I solved IE6/IE7 problem via adding extra wrapper <span /> around the block that is to be vertically aligned. This wrapper is used to imitate vertical alignment in these two non-compliant browsers, while proper layout is display in all, dare I say, normal browsers; it isn't perfect, but it works.

<html>
	<head>
		<style>
		div {
		border:3px dotted #ccc;
		height:140px;
		width:50%;
		display:table-cell;
		vertical-align:middle;
		}
		</style>
 
		<!--[if IE 7]>
			<style>
				span {margin-top:-1%;}
			</style>
		<![endif]-->
		<!--[if lt IE 7]>
			<style>
				span {margin-top:0;}
			</style>
		<![endif]-->
 
		<!--[if IE]>
			<!--[if !(IE 8)]>
				<style>
				div {
					position:relative;
				}
				span {
					height:140px;
					top:40px;
					display:inline;
					position:absolute;
					padding-top:3%;
				}
				</style>
			<![endif]-->
		<![endif]-->
	</head>
 
	<body>
 
	<div>
		<span>
			Long text that we want to vertically align in the middle in a div. Another sentense.
		<span>
	</div>
 
	</body>
</html>

In a couple of weeks, you will see how I utilized this method in production environment on slashdot user pages.

04/01/2009 update: finally I am able to reveal where I used this method: http://slashdot.org/~f1vlad/achievements, all achievements boxes are utilizing this.

|