CSS Vertical Centering
by isochronous
HTML
<div id="container">
<div id="vertcenter">
This div should be perfectly centered within its container
</div>
<button id="shuffle">Resize and re-center</button>
</div>
CSS
#container{
position: relative;
height: 600px;
background: #000;
border: 1px solid red;
}
#vertcenter{
width: 50%;
height: 300px;
position: relative; /* can also use relative or fixed depending on how you want it to act */
top: 50%;
margin-top: -150px;
margin-left: auto;
margin-right: auto;
border: 1px solid black;
background: #fff;
}
#shuffle{
position: absolute;
width: 200px;
height: 32px;
left: 5px;
bottom: 5px;
}
JavaScript
(function($){
var center = function (el, height) {
var $el = $(el),
mt = -(height/2);
$el.animate({
height: height,
"margin-top": mt + "px"
});
};
$("#shuffle").click(function () {
var newHeight = Math.random()*500,
node = $("#vertcenter");
center(node, newHeight);
});
}(jQuery));