Reputation:
I've see than this is the problem with most jquery modal popup boxes. So i'm wondering, is there any jquery code that will keep the jquery modal always centered in the page? I know this can be achieved with pure javascript code but what about jquery?
Upvotes: 2
Views: 2148
Reputation: 4617
If you are comfortable with jquery..you can use the following jquery function
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
return this;
}
Upvotes: 1
Reputation: 7315
if you want to center an element with jQuery, try this;
var browserW = $(window).width();
var centerEle = (browserW - 960) / 2; //if ur website design's width 960
$('.centeredEle').css({'left':centerEle + 'px'});//or margin-left, ur choise
Upvotes: 1
Reputation: 50905
If you're using a custom modal, a few styles that may help you are:
<div id="modal"></div>
#modal {
position: fixed;
height: 80px;
width: 200px;
left: 50%;
top: 50%;
margin-left: -40px;
margin-right: -100px;
}
The "position: fixed" keeps the modal in a certain position based on the window. Height and width obviously provide the size, while the left/margin-left and top/margin-top actually center it. The margin-left and margin-top have to be negative half of the width/height respectively.
Upvotes: 1