Take the 2-minute tour ×

This should be a simple question, but I can't seem to figure it out. I made a popup using jquery, and I want it positioned in the center of the page. No matter how the site is adjusted and the resolution. Right now I'm just positioning it absolutely with CSS but the problem with that is that if you move the page around it doesn't move the overlay and it depends on how much content is on the page. Is there a way to position it with jquery so it will also be in the center of the window?


share|improve this question
try using position:fixed instead of position:absolute. –  user1385191 Feb 20 '11 at 18:55
add comment

4 Answers

up vote 21 down vote accepted

You do not need jQuery for this. If the purpose is to always have the div in the center of the window, then you can do it with CSS.

Check working example at http://jsfiddle.net/5Q6FU/

<div class="mydiv"></div>

    margin-top:-150px; /* negative half the size of height */
    margin-left:-150px; /* negative half the size of width */
share|improve this answer
add comment

This can be done with CSS. If the popup box is absolute positioned then set left to 50% and margin-left to negative whatever half the width of the box is.

share|improve this answer
add comment

you can get window dimensions like this:

var wWidth = $(window).width();
var wHeight = $(window).height();

then you can get your popup's dimensions:

var popupWidth = $('#popupId').width();
var popupHeight = $('#popupId').height();

do some calculation:

var popupTop = (wHeight/2) - (popupHeight/2);
var popupLeft = (wWidth/2) - (popupWidth/2);

and finaly position your popup:

$('#popupId').css({'left': popupLeft, 'top': popupTop});

I haven't tested this but you should get the idea to work with.

//edit btw it would probably work just as css positioning. If you want it to reposition as the page moves you just put the code to function and call it on events when page moves.

share|improve this answer
add comment

There are a few ways to accomplish this, a good one to keep the overlay in the center even if the user resizes the window is by doing the following:

var overlay = $("#overlay"),
    top = $(window).scrollTop() - (overlay.outerHeight() / 2),
    left = -(overlay.outerWidth() / 2);

overlay.css({'margin-top': top,'margin-left': left});

and then have css (you could optionally have position fixed and get rid of the scrollTop in the javascript):

#overlay {
    position: absolute;
    left: 50%;
    z-index: 1000;
share|improve this answer
add comment

Your Answer


