This website uses cookies to personalise ads and to analyse traffic ok
web design

Center div with jQuery

How to center a fixed or fluid div vertically and horizontally with CSS & jQuery.

There are many ways for centering an element using pure CSS. The following script is useful in situations where pure CSS doesn’t really cut it (e.g. on fluid layouts, when element height is unknown or set to auto etc.). The key for centering a div within its parent element, is getting its width/height values and setting its CSS position properly and according its parent. With jQuery we can easily get those values, even if they’re not set in the CSS or they’re set as percentages. We can then make the calculations required for centering and apply the output values on the element(s).

For example, the markup below is a fluid-width div with its height set to auto:

<body>
<div id="myDiv"> 
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</body> 
body{
  margin:0;
  padding:0;
}
#myDiv{
  width:70%; 
  height:auto; 
  background:#ccc;
}

To center #myDiv within its parent element (body), we’ll create a jQuery function and pass the div id as its selector.

First, include the jQuery library inside the head tag of your html document:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

jQuery inclusion can be inserted inside the head tag or at the very bottom of your document, before the closing body tag (which is normally recommended for better performance). We also use Google’s CDN to get the jQuery library (why?).

Right after jQuery inclusion, insert the function that’ll do the trick:

<script>
  (function($){
    $(document).ready(function(){
      $.fn.center=function(){
        return this.each(function(){
          var $this=$(this),
            parent=$this.parent(),
            topPos,
            topMargin,
            leftMargin,
            resizeTimeout;
          if(parent.is("body:not(.root-height-set)")){
            $("html,body").css("height","100%").addClass("root-height-set");
          }
          if($this.css("position")==="absolute" || $this.css("position")==="fixed"){
            topPos="50%";
            topMargin="-"+Math.round($this.outerHeight()/2)+"px";
            leftMargin="-"+Math.round($this.outerWidth()/2)+"px";
            $this.css({"left":"50%","margin-left":leftMargin});
          }else{
            topPos=Math.floor((parent.height()-$this.outerHeight())/2);
            topMargin="auto";
            $this.css({"position":"relative","margin-left":"auto","margin-right":"auto"});
          }
          $this.css({"top":topPos,"margin-top":topMargin});
          $(window).resize(function(){
            if(resizeTimeout){
              clearTimeout(resizeTimeout);
            }
            resizeTimeout=setTimeout(function(){
              if($this.css("position")==="absolute"){
                topMargin="-"+Math.round($this.outerHeight()/2)+"px";
                leftMargin="-"+Math.round($this.outerWidth()/2)+"px";
                $this.css({"margin-left":leftMargin,"margin-top":topMargin});
              }else{
                topPos=Math.floor((parent.height()-$this.outerHeight())/2);
                $this.css("top",topPos);
              }
            },150);
          });
        });
      }
    });
  })(jQuery);
</script>

Note that we’re wrapping our jquery code with (function($){ ... })(jQuery);. This ensures no conflict between jquery and other libraries using $ shortcut. See Using jQuery with Other Libraries for more info. We also call our function on document ready ($(document).ready()) so the code executes by the time DOM is ready. If your element’s content contains images or other elements with external source, you should use window load instead (so code executes after all page elements are fully loaded, ensuring the script calculates correctly content’s length):

<script>
  (function($){
    $(window).load(function(){
      $.fn.center=function(){
        /* ... */
      }
    });
  })(jQuery);
</script>

Finally, we call the center function on the #myDiv:

<script>
  (function($){
    $(document).ready(function(){
      $.fn.center=function(){
        /* ... */
      }
      $("#myDiv").center();
    });
  })(jQuery);
</script>

You can change the function call selector ("#myDiv") to any type you want (an id, class name, js variable etc.) – see CSS selectors. You can also have multiple selectors by inserting comma separated values. For example, the following applies to a)every element with class name “centered” and b)the element with id “myDiv”:

$(".centered,#myDiv").center();

The complete page markup for our example should look like this:

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Center div with jQuery demo</title>
<style type="text/css">
body{
  margin:0;
  padding:0;
}
#myDiv{
  width:70%; 
  height:auto; 
  background:#ccc;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
<div id="myDiv"> 
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<script>
  (function($){
    $(document).ready(function(){
      $.fn.center=function(){
        return this.each(function(){
          var $this=$(this),
            parent=$this.parent(),
            topPos,
            topMargin,
            leftMargin,
            resizeTimeout;
          if(parent.is("body:not(.root-height-set)")){
            $("html,body").css("height","100%").addClass("root-height-set");
          }
          if($this.css("position")==="absolute" || $this.css("position")==="fixed"){
            topPos="50%";
            topMargin="-"+Math.round($this.outerHeight()/2)+"px";
            leftMargin="-"+Math.round($this.outerWidth()/2)+"px";
            $this.css({"left":"50%","margin-left":leftMargin});
          }else{
            topPos=Math.floor((parent.height()-$this.outerHeight())/2);
            topMargin="auto";
            $this.css({"position":"relative","margin-left":"auto","margin-right":"auto"});
          }
          $this.css({"top":topPos,"margin-top":topMargin});
          $(window).resize(function(){
            if(resizeTimeout){
              clearTimeout(resizeTimeout);
            }
            resizeTimeout=setTimeout(function(){
              if($this.css("position")==="absolute"){
                topMargin="-"+Math.round($this.outerHeight()/2)+"px";
                leftMargin="-"+Math.round($this.outerWidth()/2)+"px";
                $this.css({"margin-left":leftMargin,"margin-top":topMargin});
              }else{
                topPos=Math.floor((parent.height()-$this.outerHeight())/2);
                $this.css("top",topPos);
              }
            },150);
          });
        });
      }
      $("#myDiv").center();
    });
  })(jQuery);
</script>
</body> 
</html>

To make the script easier to use and implement on any page or project, you could place the function in a .js file (e.g. center.js) and include it instead of having the jQuery code on every page:

<script src="center.js"></script>
<script>
  (function($){
    $(document).ready(function(){
      $("#myDiv").center();
    });
  })(jQuery);
</script>

Cheers 🙂

Changelog

  • Sep 26, 2012
    • Updated & optimized the script.
    • Added more examples.

22 Comments

Post a comment
  1. PixelGrease
    Posted on July 19, 2012 at 17:21 Permalink

    You know, it’s funny how something to seemingly simple as a vertical center can be such a pain in the ass! I’ve spent hours and hours trying to get this sorted .. then I chanced upon your tutorials .. This is a priceless little snippet, thank you!

    Reply
  2. W. Kristianto
    Posted on July 7, 2012 at 06:26 Permalink

    Oh man.. Thanks for the great tutorial. You.. Awesome!

    Reply
  3. Will Knot B. Revealed Snr.
    Posted on June 19, 2012 at 21:55 Permalink

    For when you want to kill CSS for being so dumb >.<
    Many thanks malihu ♥

    Reply
  4. Daniele
    Posted on June 16, 2012 at 16:23 Permalink

    Mate you made my day. I just love you.

    Reply
  5. test
    Posted on May 25, 2012 at 18:26 Permalink

    testing!

    Reply
  6. malihu
    Posted on May 25, 2012 at 18:25 Permalink

    test2

    Reply
  7. malihu
    Posted on May 25, 2012 at 18:24 Permalink

    test

    Reply
  8. Ralph Almeida
    Posted on February 23, 2012 at 21:02 Permalink

    thanks a lot!

    Reply
  9. Daxel
    Posted on January 11, 2012 at 13:19 Permalink

    Didn’t do anything for me.

    Reply
  10. lasgarde
    Posted on January 4, 2012 at 13:04 Permalink

    The 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; }
    to call the function
    $(document).ready(function() { $("#idElt").center(); }); $(window).resize(function() { $("#idElt").center(); });

    Reply
  11. Roblito
    Posted on December 16, 2011 at 01:19 Permalink

    Worked for me! Thanks!

    Reply
  12. Motyar
    Posted on November 14, 2011 at 09:07 Permalink

    Why to use jQuery when its possible with CSS?

    Reply
    • malihu
      Posted on November 14, 2011 at 12:34 Permalink

      Hello,
      Most of the times you normally use css, but it requires certain conditions to be met (absolute position, known/fixed height etc.). There are occasions though that css simply doesn’t cut it. For instance when you don’t have a fixed height value.

      Reply
      • PixelGrease
        Posted on July 19, 2012 at 17:23 Permalink

        Amen to that!

        Reply
  13. Shawn
    Posted on October 8, 2011 at 07:38 Permalink

    Very Nice! Can this be done with only css/html?

    Reply
    • malihu
      Posted on October 8, 2011 at 14:41 Permalink

      Hi,
      Only if you do know the width/height of your element. For example this:
      .centered{position:absolute; left:50%; top:50%; margin:-125px 0 0 -200px; width:400px; height:250px; background:#ddd;}
      will center the div.centered on the page.
      The div needs to have fixed dimensions in order to apply the negative left and top margins which are half its width and height accordingly.

      Reply
  14. Ash
    Posted on July 18, 2011 at 05:27 Permalink

    Hello Malihu,

    Great Work! I did find an anomaly in your code though. I centered a div containing a whole bunch of form tags (Button, Text boxes etc.) When the form is posted the centering does not occur. The div shows up based upon its default properties. I even unconditionally added:
    CenterItem('.centered');
    within the Script tags to no avail. I am using the form tags within Ajax UpdatePanel.

    Regards.

    Reply
    • malihu
      Posted on July 18, 2011 at 12:33 Permalink

      Hello,
      This script needs to be updated although I haven’t check it with forms (I’ll do). I’ll update the script and post it here.

      Reply
  15. Rogério Felix
    Posted on June 27, 2011 at 14:06 Permalink

    Tkx.. very nice…

    Reply
  16. Ang
    Posted on May 29, 2011 at 19:15 Permalink

    When I have HTML, Flash, CSS, Jquery and Life problems, google brings me to your website. I’m in love with you! Thanks.

    Reply
    • malihu
      Posted on May 30, 2011 at 01:44 Permalink

      lol
      thanks Ang 😀

      Reply
  17. Kostas
    Posted on April 17, 2011 at 14:01 Permalink

    Very nice! I think it work with position absolute and with IE 6 . Thank you !

    Reply

Post a comment

Your e-mail is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
You can write or copy/paste code directly in your comment using the <code> tag:
<code>code here...</code>
You may also use the data-lang attribute to determine the code language like so:
<code data-lang-html>, <code data-lang-css>, <code data-lang-js> and <code data-lang-php>

css.php