There's a cross (desktop) browser solution to do this with CSS2 + CSS3 and without any Javascript.
Works in
- IE5+
- Gecko's (Mozilla, Firefox, Netscape 7)
- Opera 7+
- Konqueror 3+
- Webkit Browsers (Safari, Google Chrome)
- and a lot more (Mobile browsers not tested)
Documentation: Vertical Centering in CSS Definitive Solution with Unknown Height:
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
Clean jsFiddle Example: http://jsfiddle.net/WYgsP/
HTML
<div class="outerBox">
<div class="helper">
<div class="boxWithUnknownHeight">
any text<br>
any height<br>
any content, for example generated from DB<br>
everything is vertically centered
</div>
</div>
</div>
CSS
.outerBox {
display: table;
height: 400px;
#position: relative; /* ie hack */
overflow: hidden;
border: 1px solid red;
}
.helper {
#position: absolute; /* ie hack */
#top: 50%; /* ie hack */
display: table-cell;
vertical-align: middle;
}
.boxWithUnknownHeight {
#position: relative; /* ie hack */
#top: -50%;
border: 1px solid green
}
It works, even if i add text and line-breaks through Firebug etc.
To keep your CSS clean from invalid CSS-Hacks, I'll recommend you to use conditional comments for it and create a separate CSS with the browser specific Code.
How vertical centering with unknown height exactly works and why: Detailed description
Other solutions with display: table
and or display: table-cell
and or absolute positioning here.