Today I have yet another entry on HTML and CSS. Today it is how to vertically center content in HTML using CSS.
You’d think that there would be a standard definition of how to vertically center any content by now, but there isn’t. There are a variety of methods out there that do this. I frequently see people using the line-height CSS property to vertically center content. While this appears to work, it isn’t very flexible, only works properly if there is only one line of text, and doesn’t work in all situations.
I found Yuhu’s Definitive Solution with Unknown Height which looks great, works properly with all major browsers, doesn’t have the limitations I’ve seen in other solutions, and is quite simple to implement. Basically all you have to do is have three divs wrapped around the content you wish to vertically center and use specific styling for those divs.
The following code is what does the magic. Replace the comment with the content to be vertically centered, change the height to match the vertical height of the container, and you’re set.
<div style="display:table; height:400px; #position:relative;">
<div style="#position:absolute; #top:50%; display:table-cell; vertical-align:middle;">
<div style="#position:relative; #top:-50%">
<!-- content to be centered -->
</div>
</div>
</div>
I built a quick example document that shows how I applied the rules via a style block in the head to keep the HTML clean.
As with my taming HTML lists fix, I tested this successfully on the following browsers:
- OS X
- Firefox 3.5
- Safari 4
- Ubuntu (Linux)
- Firefox 3.5
- Google Chrome 4
- Konqueror 4.2
- Midori 0.1.2
- Opera 10
- Windows
- Firefox 3.5
- Google Chrome 4
- Internet Explorer 6, 7, and 8
- Safari 4
Thank you Yuhu for the great solution.
Did I help you?