775

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

John Slegers
  • 38,420
  • 17
  • 182
  • 152
Craig
  • 34,658
  • 33
  • 108
  • 191
  • 21
    This is more of a CSS question than a jQuery question. You can use jQuery methods to help you find the cross-browser positioning and to apply the proper CSS styles to an element, but the essence of the question is how to center a div on the screen using CSS. – Chris MacDonald Oct 17 '08 at 00:20
  • Here is one more plugin. http://www.alexandremagno.net/jquery/plugins/center/ – Ivailo Bardarov Feb 01 '11 at 18:27
  • 2
    If you are centering a div on the screen, you may be using FIXED positioning. Why not just do this: http://stackoverflow.com/questions/2005954/margin-to-center-with-position-fixed. The solution is pure CSS, doesn't require javascript. – Ardee Aram Apr 14 '11 at 02:00
  • Agree, JavaScript method isn't that friendly at all. Especially cross browser. – Simon Hayter Jan 17 '13 at 22:07

28 Answers28

1077

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)

JGrinon
  • 1,421
  • 1
  • 14
  • 34
Tony L.
  • 7,947
  • 5
  • 22
  • 28
  • 78
    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. – Trevor Burnham Jan 25 '10 at 20:52
  • 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. – Rich Jul 26 '10 at 15:09
  • But outherHeight and outerWidth are only supported by Firefox, right? – Max Kielland Jul 06 '11 at 10:24
  • 83
    Why isn't this a native part of jQuery's functionality? – Seth Carnegie Jul 06 '11 at 21:54
  • 1
    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? – aalaap Dec 06 '11 at 09:41
  • 14
    What if I dont want to center in the containing `
    ` instead of ``? Maybe you should change `window` to `this.parent()` or add a parameter for it.
    – Derek 朕會功夫 Feb 21 '12 at 04:59
  • 1
    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. – Zaptree Apr 16 '12 at 15:23
  • 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)` – Muleskinner Apr 25 '12 at 09:24
  • 13
    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. – Diego Jun 06 '12 at 15:43
  • 2
    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. – Webnet Jul 16 '12 at 12:27
  • 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: http://jsfiddle.net/m6D72/ – Alex Jorgenson Oct 02 '12 at 01:32
  • Instead of this.outerHeight() should be $(this).outerHeight() sameas $(this).outerWidth(). Otherwise you probably get "outerHeight is not a function" error. (http://stackoverflow.com/questions/947692/outerheight-is-not-a-function) – Berkay Turancı Dec 07 '12 at 12:37
  • jQuery already has a center function.. Why don't you change the name! – Adam F Dec 20 '12 at 17:21
  • 2
    To use fixed positioning instead of absolute, just remove the `+ $(window).scrollTop()` and `+ $(window).scrollLeft()`. (And, of course, change `"absolute"` to `"fixed"`). – Katie Kilian Sep 17 '13 at 19:06
  • 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.. – Anees Hikmat Abu Hmiad Jul 16 '14 at 09:23
  • 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(); – josh.thomson Jun 29 '15 at 09:17
  • Why use $(this).outerHeight() instead of this.outerHeight()? – Silence Peace Feb 05 '16 at 21:32
  • How would you animate this? – Nic Scozzaro May 06 '19 at 21:17
145

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%;
}
Community
  • 1
  • 1
molokoloco
  • 4,126
  • 2
  • 29
  • 26
  • Your function worked perfectly fine for a vertical center. It does not appear to work for a horizontal center. – Halsafar Jun 01 '12 at 02:50
  • The CSS assumes you know the size (percentages at least) of the centered div, whereas the jQuery works whatever. – Dunc Jan 22 '14 at 09:16
  • 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 – user1616338 Oct 03 '19 at 16:35
63

I would recommend jQueryUI Position utility

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

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

cetnar
  • 9,141
  • 2
  • 36
  • 44
40

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;
}
Juho Vepsäläinen
  • 24,765
  • 11
  • 73
  • 98
  • 3
    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.) – Darren Cook Jul 08 '12 at 08:46
  • 1
    Sometimes you may want to use `outerWidth()` and `outerHeight()` to consider padding and border width. – Philippe Gerber May 16 '13 at 01:08
  • This works perfectly for me for legacy project with doc type 5 where `$(window).height()` gives 0. But I've changed position to 'absolute'. – Mike Dec 19 '16 at 10:55
27

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

apaul
  • 15,557
  • 8
  • 44
  • 76
  • Keep in mind calc() is not supported in IE8 if you need to support that browser use the jquery center strategy. – mbokil Aug 25 '13 at 23:15
15

I'm expanding upon the great answer given by @TonyL. I'm adding Math.abs() to wrap the values, and also I take into account that jQuery might be in "no conflict" mode, like for instance in WordPress.

I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.

The other thing I do is speed this up a bit by caching the $(window) object so that I reduce extra DOM traversals, and I use a cluster CSS.

jQuery.fn.center = function ($) {
  var w = $(window);
  this.css({
    'position':'absolute',
    'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
    'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
  });
  return this;
}

To use, you would do something like:

jQuery(document).ready(function($){
  $('#myelem').center();
});
Volomike
  • 21,378
  • 19
  • 99
  • 188
  • 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 Oct 02 '12 at 01:21
12

I would use the jQuery UI position function.

See working demo.

<div id="test" style="position:absolute;background-color:blue;color:white">
    test div to center in window
</div>

If i 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>
atiquratik
  • 1,154
  • 3
  • 22
  • 30
andy_edward
  • 171
  • 1
  • 4
9

I would like to correct one issue.

this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");

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.

atiquratik
  • 1,154
  • 3
  • 22
  • 30
John Butcher
  • 91
  • 1
  • 1
7

This is untested, but something like this should work.

var myElement = $('#myElement');
myElement.css({
    position: 'absolute',
    left: '50%',
    'margin-left': 0 - (myElement.width() / 2)
});
Andrew Hedges
  • 21,058
  • 16
  • 62
  • 78
6

I dont think having an absolute position would be best if you want an element always centered in the middle of the page. You probably want a fixed element. I found another jquery centering plugin that used fixed positioning. It is called fixed center.

Fred
  • 61
  • 1
  • 1
4

To center the element relative to the browser viewport (window), don't use position: absolute, the correct position value should be fixed (absolute means: "The element is positioned relative to its first positioned (not static) ancestor element").

This alternative version of the proposed center plugin uses "%" instead of "px" so when you resize the window the content is keep centered:

$.fn.center = function () {
    var heightRatio = ($(window).height() != 0) 
            ? this.outerHeight() / $(window).height() : 1;
    var widthRatio = ($(window).width() != 0) 
            ? this.outerWidth() / $(window).width() : 1;

    this.css({
        position: 'fixed',
        margin: 0,
        top: (50*(1-heightRatio)) + "%",
        left: (50*(1-widthRatio))  + "%"
    });

    return this;
}

You need to put margin: 0 to exclude the content margins from the width/height (since we are using position fixed, having margins makes no sense). According to the jQuery doc using .outerWidth(true) should include margins, but it didn't work as expected when I tried in Chrome.

The 50*(1-ratio) comes from:

Window Width: W = 100%

Element Width (in %): w = 100 * elementWidthInPixels/windowWidthInPixels

Them to calcule the centered left:

 left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
 = 50 * (1-elementWidthInPixels/windowWidthInPixels)
Diego
  • 3,973
  • 1
  • 19
  • 21
4

The transition component of this function worked really poorly for me in Chrome (didn't test elsewhere). I would resize the window a bunch and my element would sort of scoot around slowly, trying to catch up.

So the following function comments that part out. In addition, I added parameters for passing in optional x & y booleans, if you want to center vertically but not horizontally, for example:

// Center an element on the screen
(function($){
  $.fn.extend({
    center: function (x,y) {
      // var options =  $.extend({transition:300, minX:0, minY:0}, options);
      return this.each(function() {
                if (x == undefined) {
                    x = true;
                }
                if (y == undefined) {
                    y = true;
                }
                var $this = $(this);
                var $window = $(window);
                $this.css({
                    position: "absolute",
                });
                if (x) {
                    var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
                    $this.css('left',left)
                }
                if (!y == false) {
            var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();   
                    $this.css('top',top);
                }
        // $(this).animate({
        //   top: (top > options.minY ? top : options.minY)+'px',
        //   left: (left > options.minX ? left : options.minX)+'px'
        // }, options.transition);
        return $(this);
      });
    }
  });
})(jQuery);
4

This is great. I added a callback function

center: function (options, callback) {


if (options.transition > 0) {
   $(this).animate(props, options.transition, callback);
} else { 
    $(this).css(props);
   if (typeof callback == 'function') { // make sure the callback is a function
       callback.call(this); // brings the scope to the callback
   }
}
Leo the lion
  • 3,213
  • 2
  • 19
  • 39
Keith
  • 41
  • 1
4

Edit:

If the question taught me anything, it's this: don't change something that already works :)

I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:

.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper    {#position:absolute; #top:50%;
            display:table-cell; vertical-align:middle;}
.content   {#position:relative; #top:-50%;
            margin:0 auto; width:200px; border:1px solid orange;}

Fiddle: http://jsfiddle.net/S9upd/4/

I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.

Original:

Looks like I'm late to the party!

There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:

.container {
    position:absolute;
    left: 50%;
    top: 50%;
    overflow:visible;
}
.content {
    position:relative;
    margin:-50% 50% 50% -50%;
}

Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/

Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.


Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:

<table class="super-centered"><tr><td>
    <div class="content">
        <p>I am centered like a boss!</p>
    </div>
</td></tr></table>

And than the content's position is fine-tuned with good old margin:0 auto;:

.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}​

Working fiddle as promised: http://jsfiddle.net/teDQ2/

Solomon Ucko
  • 2,682
  • 2
  • 14
  • 27
Oleg
  • 22,838
  • 4
  • 55
  • 82
  • 1
    The problem is that isn't centered. – Konrad Borowski Mar 18 '12 at 13:10
  • @GlitchMr: I'd like to double check on the work box tomorrow, but the second fiddle worked fine on Chrome/Safari Mac – Oleg Mar 18 '12 at 13:50
  • 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. – Konrad Borowski Mar 18 '12 at 14:23
  • @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! :) – Oleg Mar 18 '12 at 22:25
  • 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 Mar 19 '12 at 06:24
  • Actually, my mistake. I haven't read and I thought that you've updated lowest fiddle (http://jsfiddle.net/teDQ2/). Current solution works fine in IE7. – Konrad Borowski Mar 19 '12 at 15:40
3

What I have here is a "center" method that ensures the element you are attempting to center is not only of "fixed" or "absolute" positioning, but it also ensures that the element you are centering is smaller than its parent, this centers and element relative to is parent, if the elements parent is smaller than the element itself, it will pillage up the DOM to the next parent, and center it relative to that.

$.fn.center = function () {
        /// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>

        var element = $(this),
            elementPos = element.css('position'),
            elementParent = $(element.parent()),
            elementWidth = element.outerWidth(),
            parentWidth = elementParent.width();

        if (parentWidth <= elementWidth) {
            elementParent = $(elementParent.parent());
            parentWidth = elementParent.width();
        }

        if (elementPos === "absolute" || elementPos === "fixed") {
            element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
        }
    };
Ryan
  • 285
  • 1
  • 8
2

i use this:

$(function() {
   $('#divId').css({
    'left' : '50%',
    'top' : '50%',
    'position' : 'absolute',
    'margin-left' : -$('#divId').outerWidth()/2,
    'margin-top' : -$('#divId').outerHeight()/2
  });
});
holden
  • 1,505
  • 10
  • 18
2

Please use this:

$(window).resize(function(){
    $('.className').css({
        position:'absolute',
        left: ($(window).width() - $('.className').outerWidth())/2,
        top: ($(window).height() - $('.className').outerHeight())/2
    });
});

// To initially run the function:
$(window).resize();
Tunaki
  • 116,530
  • 39
  • 281
  • 370
satya
  • 1,039
  • 8
  • 11
1

CSS solution In two lines only

It centralize your inner div horizontally and vertically.

#outer{
  display: flex;
}
#inner{
  margin: auto;
}

for only horizontal align, change

margin: 0 auto;

and for vertical, change

margin: auto 0;
Rayees AC
  • 4,008
  • 3
  • 6
  • 27
Shivam Chhetri
  • 567
  • 8
  • 13
0

Here is my version. I may change it after I look at these examples.

$.fn.pixels = function(property){
    return parseInt(this.css(property));
};

$.fn.center = function(){
    var w = $($w);
    return this.each(function(){
        $(this).css("position","absolute");
        $(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
        $(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
    });
};
Andrew
  • 3,067
  • 1
  • 27
  • 33
0

No need jquery for this

I used this to center Div element. Css Style,

.black_overlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}

.white_content {
    display: none;
    position: absolute;
    top: 25%;
    left: 25%;
    width: 50%;
    height: 50%;
    padding: 16px;
    border: 16px solid orange;
    background-color: white;
    z-index:1002;
    overflow: auto;
}

Open element

$(document).ready(function(){
    $(".open").click(function(e){
      $(".black_overlay").fadeIn(200);
    });

});
Sajitha Rathnayake
  • 1,576
  • 1
  • 23
  • 43
0

You could use the CSS translate property:

position: absolute;
transform: translate(-50%, -50%);

Read this post for more details.

Fred K
  • 11,133
  • 13
  • 70
  • 90
  • 1
    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. – Fata1Err0r Jul 23 '15 at 15:44
0

MY UPDATE TO TONY L'S ANSWER This is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of position or only wanting horizontal/vertical centering rather than both.

center.js:

// We add a pos parameter so we can specify which position type we want

// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
    this.css("position", pos);
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it vertically only
jQuery.fn.centerVer = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    return this;
}

In my <head>:

<script src="scripts/center.js"></script>

Examples of usage:

$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")

$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")

$("#example5").center("absolute")
$("#example6").center("fixed")

It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly.

Hope this is useful for someone out there! Enjoy.

Fata1Err0r
  • 706
  • 1
  • 5
  • 11
0

you're getting that poor transition because you're adjusting the position of the element every time the document is scrolled. What you want is to use fixed positioning. I tried that fixed center plugin listed above and that seems to do solve the problem nicely. Fixed positioning allows you to center an element once, and the CSS property will take care of maintaining that position for you every time you scroll.

skaterdav85
  • 576
  • 2
  • 9
  • 26
0

Lot's of ways to do this. My object is kept hidden with display:none just inside the BODY tag so that positioning is relative to the BODY. After using $("#object_id").show(), I call $("#object_id").center()

I use position:absolute because it is possible, especially on a small mobile device, that the modal window is larger than the device window, in which case some of the modal content could be inaccessible if positioning was fixed.

Here's my flavor based on other's answers and my specific needs:

$.fn.center = function () {
        this.css("position","absolute");

        //use % so that modal window will adjust with browser resizing
        this.css("top","50%");
        this.css("left","50%");

        //use negative margin to center
        this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
        this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");

        //catch cases where object would be offscreen
        if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
        if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});

        return this;
    };
i_a
  • 2,660
  • 1
  • 18
  • 20
0

Normally, I would do this with CSS only... but since you asked you a way to do this with jQuery...

The following code centers a div both horizontally and vertically inside its container :

$("#target").addClass("centered-content")
            .wrap("<div class='center-outer-container'></div>")
            .wrap("<div class='center-inner-container'></div>");
body {
    margin : 0;
    background: #ccc;
}

.center-outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;
}

.center-inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="target">Center this!</div>

(see also this Fiddle)

John Slegers
  • 38,420
  • 17
  • 182
  • 152
0

Just say: $("#divID").html($('').html($("#divID").html()));

1.618
  • 779
  • 1
  • 10
  • 16
0

It can be done with only CSS. But they asked with jQuery or JavaScript

Here, use CSS Flex box property to align the div center.

body.center{
  display:flex;
  align-items:center; // Vertical alignment
  justify-content:center; // Horizontal alignment
}

align-items:center; - used to align vertically.

justify-content:center; - used to align horizontally.

document.querySelector("body").classList.add("center");
body {
  margin : 0;
  height:100vh;
  width:100%;
  background: #ccc;
}
#main{
  background:#00cc00;
  width:100px;
  height:100px;
}
body.center{
  display:flex;
  align-items:center;
  justify-content:center;
}
<body>
  <div id="main"></div>
</body>
Rayees AC
  • 4,008
  • 3
  • 6
  • 27
-6

Why you don't use CSS for centering a div?

#timer_wrap{  
  position: fixed;
  left: 50%;
  top: 50%;
} 
Yi Jiang
  • 46,385
  • 16
  • 133
  • 131