Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

position an overlay in the center of the page with jquery

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?

Thanks!

like image 496
Bill Avatar asked Feb 20 '11 18:02

Bill


People also ask

What is overlay in jQuery?

A jQuery selector for the closing elements inside the overlay. These can be any elements such as links, buttons or images. If this is not supplied, a close element is auto-generated.

What is position jQuery?

The position() method is an inbuilt method in jQuery which is used to find the position of the first matched element relative to its parent element in the DOM tree. Syntax: $(selector).position()

How do I overlay a button in a div?

Answer: Use the CSS z-index Property You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element.


3 Answers

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>

.mydiv{
    width:300px;
    height:300px;
    background:red;
    position:fixed;
    top:50%;
    left:50%;
    margin-top:-150px; /* negative half the size of height */
    margin-left:-150px; /* negative half the size of width */
}
like image 76
Hussein Avatar answered Sep 23 '22 20:09

Hussein


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.

like image 28
Voooza Avatar answered Sep 21 '22 20:09

Voooza


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.

like image 31
Will Avatar answered Sep 22 '22 20:09

Will