Welcome to Code Couch

How do you vertically centre content using CSS?

Posted by at 1:12pm on October 28, 2008.

How do you vertical centre some content using CSS (and some extra div elements)? This is the same simple layout that used to be achieved using a table and valign attribute. This solution doesn’t require a table at all (but it does require some extra div elements – as per the markup below).

With the following markup:

<div class="verticalCenteringOuter" id="moduleA">
	<div class="verticalCenteringMiddle">
		<div class="verticalCenteringInner">
			<b>Some vertical aligned content here</b>
		</div>
	</div>
</div>

Using the following CSS:

<style type="text/css">
#moduleA {
	height: 300px;
}
.verticalCenteringOuter {
	display: table;
	overflow: hidden;
}
.verticalCenteringMiddle {
	display: table-cell;
	vertical-align: middle;
}
</style>
 
<!--[if IE]>
<style type="text/css">
.verticalCenteringOuter {
	position: relative;
}
.verticalCenteringMiddle {
	position: absolute;
	top: 50%;
}
.verticalCenteringInner {
	position: relative;
	top: -50%;
}
</style>
<![endif]-->

Full credit on this to Yuhů (www.jakpsatweb.cz). Thanks for the inspiration on this one.

Post to Twitter

Tags:

Comments

There are no responses to this post.

Leave a reply

Comments are closed for this post.