0

Here is my code, but it doesn't work (the div always floats to the top of the page. I want it to be located in the center of the page).

HTML:

<div id="overlay">Stuff</div>

JQuery:

$(document).ready(function(){
    var height = $('#overlay').height();
    var marginTop = (height)/2;
    document.getElementById("overlay").style.marginTop="-"+marginTop+"px";
    document.getElementById("overlay").style.top="50%";
});

What am I doing wrong?

Aaron Brokmeier
  • 41
  • 1
  • 2
  • 8

1 Answers1

1
$(document).ready(function(){
    resize();
    $(window).resize(resize);
});

function resize()
{
    var height = $('#overlay').height();
    $('#overlay').css('margin-top', (($(window).height() - height) / 2) + 'px');
}

Remember, you want the window height minus the overlay height. Then divide by two and you have your desired margin.

Kai Qing
  • 18,793
  • 5
  • 39
  • 57
  • Thanks! I noticed that if I resize the window, then the div stays where it is, instead of "readjusting" to the new window size. How can I set your script to adjust upon window resizing? – Aaron Brokmeier Oct 31 '12 at 01:52