RSS

How to vertically align content in CSS

Sat, Aug 16, 2008

CSS

Have you ever used vertical-align: middle in a block of CSS without it ever working? You too, huh? This article will show you a method on how to center content properly with CSS only.

The table-cell method

The CSS specification declares that vertical-align only refers to table cells. When applied to other elements, like in most cases - divs, the alignment will not work. After all, we want to mimic theĀ <td valign="middle"> attribute. For this to work, the parent element needs to have a given fixed height. The content you want to vertically centered does not have to have a fixed height.

Here is how to center an image in a div with only CSS (and CSS expression for Internet Explorer).

<html>
	<head>
	<style type="text/css">
	.content
	{
		width: 200px
		height: 200px
		display: table-cell
		vertical-align: middle
		text-align: center
		border: 1px solid red
	}
	.content img
	{
		margin-top: expression((200 - this.height)/2)
	}
 
	</style>
	</head>
	<body>
		<div class="content">
			<img src="wordpress.png" />
		</div>
 
		<div class="content">
			<img src="prado.png" />
		</div>
	</body>
</html>

display: table-cell og vertical-align: middle in the .content declaration seems like the correct thing to do. And it is, but unfortunately display: table-cell doesn’t work on Internet Explorer versions prior to 7.0. Expressions for CSS (Dynamic Properties for Internet Explorer) can help us fix this problem. Watch this:

margin-top: expression((100 - this.height) / 2);

Explained: [the height of the parent element] / [the height of the image we want to center] / 2. The result leaves us the margin spacing we need between the img and the edges of the div. If we set this calculation as margin-top, the img will be centered. In the results below, we clearly see two different img elements in size being placed in the middle of the parent div, with the same block of CSS code.

Expected result

This solution has been tested in IE5/6/7, Firefox 2/3, Opera 9 and Safari 2.

Leave a Reply