Sometimes I need to centre dynamic content vertically within an area. This used to be a doddle with tables, valign=”middle” was all you needed. However, in the world of div tags and css this isn’t acceptable anymore.
So, I figured jQuery must be able to help out - why not, it can do everything else!
HTML
<div class="container">
<div class="box">Vertical content of unknown height</div>
</div>
CSS
.container { float:left; width:380px; height:380px; }
.container .box { float:left; width:200px; margin-left:90px; }
jQuery
$(document).ready(function(){
var top = ( $('.container').height() - $('.container .box').height() ) / 2;
$('.container .box').css('margin-top', top);
});
