2

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?

  • are you talking about a non-jqueryUI modal? – Ian Jul 07 '12 at 00:16
  • duplicate question: http://stackoverflow.com/questions/7557068/jquery-dialog-always-centered one of the answers there has a jsFiddle example.. – Ann B. G. Jul 07 '12 at 00:34

3 Answers3

1

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.

Ian
  • 50,146
  • 13
  • 101
  • 111
1

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
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
1

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;
}
Sibu
  • 4,609
  • 2
  • 26
  • 38