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));Written by Jeremy McLeod
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#