javascript tutorial - [Solved-5 Solutions] Using jQuery to center a DIV on the screen - javascript - java script - javascript array



Problem:

How to set a <div> in the center of the screen using jQuery ?

Solution 1:

We like adding functions to jQuery so this function would help:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}
click below button to copy the code. By JavaScript tutorial team

Now we can just write:

$(element).center();
click below button to copy the code. By JavaScript tutorial team

Solution 2:

We would recommend jQueryUWE Position utility

$('your-selector').position({
    of: $(window)
});
click below button to copy the code. By JavaScript tutorial team

which gives we much more possibilities than only centering ...

Solution 3:

Here's my go at it. We ended up using it for my Lightbox clone. The main advantage of this solution is that the element will stay centered automatically even if the window is resized making it ideal for this sort of usage.

$.fn.center = function() {
    this.css({
        'position': 'fixed',
        'left': '50%',
        'top': '50%'
    });
    this.css({
        'margin-left': -this.outerWidth() / 2 + 'px',
        'margin-top': -this.outerHeight() / 2 + 'px'
    });

    return this;
}

click below button to copy the code. By JavaScript tutorial team

Solution 4:

We would use the jQuery UI position function.

<div id="test" style="position:absolute;background-color:blue;color:white">
    test div to center in window
</div>
click below button to copy the code. By JavaScript tutorial team

If we have a div with id "test" to center then the following script would center the div in the window on document ready. (the default values for "my" and "at" in the position options are "center")

<script type="text/javascript">
$(function(){
  $("#test").position({
     of: $(window)
  });
};
</script>

click below button to copy the code. By JavaScript tutorial team

Solution 5:

We would like to correct one issue.

this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
click below button to copy the code. By JavaScript tutorial team

Above code won't work in cases when this.height (lets assume that user resizes the screen and content is dynamic) and scrollTop() = 0,

example:

window.height is 600
this.height is 650
600 - 650 = -50  

-50 / 2 = -25

Now the box is centered -25 offscreen


Related Searches to javascript tutorial - Using jQuery to center a DIV on the screen