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!
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.
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()
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.
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.
<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 */
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With