Last Updated: September 09, 2019
·
1.71K
· 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));

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside