Search code examples
javascriptalignmentcenter

Vertically align using margin-top


I'm trying to vertically centre my division.

I need something that tells the 'margin-top' to -50% of the division.

You can see it here: http://jsfiddle.net/N5gsW/

I know I'm doing something wrong :(

Thanks

HTML

<body>
<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent iaculis quam non massa venenatis malesuada. Ut mollis, nibh id placerat euismod, magna lectus sodales lacus, nec ultrices.
</div>

CSS

body{
margin: 0 0 0 0;
width: 100%;
height: 100%;
padding: 0 0 0 0;
}
#content{
width: 100px;
left: 50%;
margin-left: -50px;
top: 50%; 
position: fixed;
background: #0C6;
}

Javascript

$(document).ready(function() {

$('#content').each(function() {
    var parentHeight = $(this).parent().height();
    var thisHeight = $(this).height();
    var topmargin = (parentHeight - thisHeight) / 2;
    $(this).css("margin-top", topmargin);
});
})  

Solution

  • The margin top needs to be -50px, worked out like so

    margin-top = -(height / 2)px