Last Updated: September 09, 2019
·
1.486K
· isochronous

Easy vertical centering with CSS

See the fiddle for a more detailed demonstration
http://jsfiddle.net/isochronous/kcsvU/

<div id="container">
    <div id="vertcenter">
        This div should be perfectly vertically centered within its container
    </div>
</div>

<style>
#container{
    position: relative;
    height: 800px;
}
#vertcenter{
    width: 50%;
    height: 480px;
    position: relative; /*can also use absolute or fixed if you want the element out of the page flow*/
    top: 50%;
    margin-top: -240px;
    border: 1px solid black;
}
</style>

You can easily use javascript (jQuery makes it even easier) to do this to any element:

(function($){
    var h = $("#vertcenter");
    h.css({
        position: "relative",
        top: "50%",
        "margin-top": -(h.outerHeight()/2) + "px"
    })
}(jQuery));