Using jQuery to center a DIV on the screen

529,130

Solution 1

I 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;
}

Now we can just write:

$(element).center();

Demo: Fiddle (with added parameter)

Solution 2

I put a jquery plugin here

VERY SHORT VERSION

$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});

SHORT VERSION

(function($){
    $.fn.extend({
        center: function () {
            return this.each(function() {
                var top = ($(window).height() - $(this).outerHeight()) / 2;
                var left = ($(window).width() - $(this).outerWidth()) / 2;
                $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
            });
        }
    }); 
})(jQuery);

Activated by this code :

$('#mainDiv').center();

PLUGIN VERSION

(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside:window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
                    vertical:true, // booleen, center vertical
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);

Activated by this code :

$(document).ready(function(){
    $('#mainDiv').center();
    $(window).bind('resize', function() {
        $('#mainDiv').center({transition:300});
    });
);

is that right ?

UPDATE :

From CSS-Tricks

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); /* Yep! */
  width: 48%;
  height: 59%;
}

Solution 3

I would recommend jQueryUI Position utility

$('your-selector').position({
    of: $(window)
});

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

Solution 4

Here's my go at it. I 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;
}

Solution 5

You can use CSS alone to center like so:

Working Example

.center{
    position: absolute;
    height: 50px;
    width: 50px;
    background:red;
    top:calc(50% - 50px/2); /* height divided by 2*/
    left:calc(50% - 50px/2); /* width divided by 2*/
}
<div class="center"></div>

calc() allows you to do basic calculations in css.

MDN Documentation for calc()
Browser support table

Share:
529,130
Craig
Author by

Craig

Buy my software!

Updated on July 22, 2022

Comments

  • Craig
    Craig almost 2 years

    How do I go about setting a <div> in the center of the screen using jQuery?

  • Trevor Burnham
    Trevor Burnham over 14 years
    One change I'd suggest: You should use this.outerHeight() and this.outerWidth() instead of just this.height() and this.width(). Otherwise, if the object has a border or padding, it will end up slightly off-center.
  • Rich
    Rich almost 14 years
    I found that this worked great except in IE7/IE8 compatibility mode, where my element was shunted to the right by a fair bit. molokoloco's below solution worked cross-browser for me.
  • Max Kielland
    Max Kielland almost 13 years
    But outherHeight and outerWidth are only supported by Firefox, right?
  • Seth Carnegie
    Seth Carnegie almost 13 years
    Why isn't this a native part of jQuery's functionality?
  • aalaap
    aalaap over 12 years
    This plugin/function works amazingly. I'm wondering, though, if it's possible to also add corner alignment options such as .bottomRight() or .leftTop() or something similar?
  • Derek 朕會功夫
    Derek 朕會功夫 over 12 years
    What if I dont want to center in the containing <div> instead of <body>? Maybe you should change window to this.parent() or add a parameter for it.
  • Cristi Mihai
    Cristi Mihai over 12 years
    In your example, the div's top/left will be where the center supposed to be.
  • Konrad Borowski
    Konrad Borowski over 12 years
    The problem is that isn't centered.
  • Oleg
    Oleg over 12 years
    @GlitchMr: I'd like to double check on the work box tomorrow, but the second fiddle worked fine on Chrome/Safari Mac
  • Konrad Borowski
    Konrad Borowski over 12 years
    Right, I've checked in Chrome, Firefox and Internet Explorer 8+ (IE7 doesn't work) and it works. But it doesn't work in Opera... and that's very weird considering it's simple CSS and it works in other browsers.
  • Oleg
    Oleg over 12 years
    @GlitchMr: thanks for keeping an eye on such an old question. I've updated the fiddle link above to show a "correct" answer - let me know if it works for you (or downvote into oblivion. I've had my chance! :)
  • Konrad Borowski
    Konrad Borowski over 12 years
    Heh, all I will do is not upvoting unless proper answer will show (currently it still doesn't work in Opera, but I think it's browser bug)... oh wait... it works if I will resize the window and not if I will resize windows in JSFiddle itself. So, it works :). I'm sorry for this. But still, you should put warning that it doesn't work in IE7. +1. Oh, and I think it works in IE6...
  • Konrad Borowski
    Konrad Borowski over 12 years
    Actually, my mistake. I haven't read and I thought that you've updated lowest fiddle (jsfiddle.net/teDQ2). Current solution works fine in IE7.
  • Zaptree
    Zaptree about 12 years
    One problem with this is that if the element is higher or wider than the window then it will end up being placed with a negative top or left positioning meaning the user will not be able to scroll and see the whole thing. You should set top and left to 0 if they end up being negative.
  • Muleskinner
    Muleskinner about 12 years
    I believe you should subtract half the height of the div you want to center, ie add this to the "top" code: - (this.outerHeight() / 2)
  • Halsafar
    Halsafar about 12 years
    Your function worked perfectly fine for a vertical center. It does not appear to work for a horizontal center.
  • Diego
    Diego about 12 years
    The code in the answer should use "position: fixed" since "absolute" is calculated from the first relative parent, and the code uses window to calculate the center.
  • Darren Cook
    Darren Cook almost 12 years
    I think this works well... it went wrong in my case because of using responsive design: my div's width changes as screen width changes. What does work perfectly is Tony L's answer and then adding this: $(window).resize(function(){$('#mydiv').center()}); (mydiv is a modal dialog, so when it is closed I remove the resize event handler.)
  • Ben
    Ben almost 12 years
    I would also suggest adding support so that when the window is resized it'll adjust the element on the page. Currently it stays with the original dimensions.
  • Alex Jorgenson
    Alex Jorgenson over 11 years
    I like your improvements; however, there is still one issue I found depending on the exact behavior you are looking for. The abs will work great only if the user is fully scrolled to the top and left, otherwise the user will have to scroll the browser window to get to the title bar. To solve that problem I opted to do a simple if statement such as this: if (top < w.scrollTop()) top = w.scrollTop(); along with the equivalent for left. Again, this provides different behavior that may or may not be desirable.
  • Alex Jorgenson
    Alex Jorgenson over 11 years
    This is a great piece of code that I am now using to help with my custom fixes to the jQuery UI Dialog functionality (auto height + max height = jQuery UI Dialog no like). I modified the code slightly so that if the element being centered doesn't fit into the entire window, the top and left are set to the maximum values required to ensure that the top and left of the element are always visible. This works great for things like dialog boxes so the user can always access the title bar of the dialog box to move and close it. The fork of his code is here: jsfiddle.net/m6D72
  • Berkay Turancı
    Berkay Turancı over 11 years
    Instead of this.outerHeight() should be $(this).outerHeight() sameas $(this).outerWidth(). Otherwise you probably get "outerHeight is not a function" error. (stackoverflow.com/questions/947692/…)
  • Adam F
    Adam F over 11 years
    jQuery already has a center function.. Why don't you change the name!
  • keithhackbarth
    keithhackbarth over 11 years
    @Timwi - Are you sure you are centering on window vs. document?
  • Michelangelo
    Michelangelo about 11 years
    TypeError: $(...).position is not a function
  • Philippe Gerber
    Philippe Gerber about 11 years
    Sometimes you may want to use outerWidth() and outerHeight() to consider padding and border width.
  • jake
    jake about 11 years
    @Michelangelo: You need the jqueryUI library to use .position() as a function. Check out: api.jqueryui.com/position/
  • mbokil
    mbokil almost 11 years
    Keep in mind calc() is not supported in IE8 if you need to support that browser use the jquery center strategy.
  • Katie Kilian
    Katie Kilian almost 11 years
    To use fixed positioning instead of absolute, just remove the + $(window).scrollTop() and + $(window).scrollLeft(). (And, of course, change "absolute" to "fixed").
  • Cԃաԃ
    Cԃաԃ over 10 years
    That snippet is the best :D. But be warn the element must be "visible".'
  • Dunc
    Dunc over 10 years
    The CSS assumes you know the size (percentages at least) of the centered div, whereas the jQuery works whatever.
  • Anees Hikmat Abu Hmiad
    Anees Hikmat Abu Hmiad almost 10 years
    thanks mate, Im declare my custom code to center any element, buts now when I read your function, really is very nice, ease ..Im like it very much, I will use this Now ^_^...nice..
  • josh.thomson
    josh.thomson about 9 years
    This is fantastic, however... how would I make this a toggle? ...so that I can revert the centering in a different scenario? aka.. $(element).nocenter();
  • Fata1Err0r
    Fata1Err0r almost 9 years
    For something like that, you would want to set your left: 50% and top: 50% then you can use the transform translate to shift its center point over correctly. However, with this method, browsers such as Chrome will distort/blur your text afterwards, which isn't usually desirable. It's better to grab the width/height of the window, and then position the left/top based upon that instead of messing with the transform. Prevents distortion and works across every browser I've tested it on.
  • Silence Peace
    Silence Peace over 8 years
    Why use $(this).outerHeight() instead of this.outerHeight()?
  • Ben
    Ben almost 8 years
    Did you forget to include the html to your answer?
  • Mike
    Mike over 7 years
    This works perfectly for me for legacy project with doc type 5 where $(window).height() gives 0. But I've changed position to 'absolute'.
  • Nic Scozzaro
    Nic Scozzaro about 5 years
    How would you animate this?
  • user1616338
    user1616338 over 4 years
    My vote is CSS - much more straightforward and doesn't need any fancy Java script. If you use fixed instead of absolute it'll stay in center of page even when the user scrolls the browser window