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.
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!
Oh man.. Thanks for the great tutorial. You.. Awesome!
For when you want to kill CSS for being so dumb >.<
Many thanks malihu ♥
Mate you made my day. I just love you.
testing!
test2
test
thanks a lot!
Didn’t do anything for me.
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(); });
Worked for me! Thanks!
Why to use jQuery when its possible with CSS?
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.
Amen to that!
Very Nice! Can this be done with only css/html?
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.
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.
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.
Tkx.. very nice…
When I have HTML, Flash, CSS, Jquery and Life problems, google brings me to your website. I’m in love with you! Thanks.
lol
thanks Ang 😀
Very nice! I think it work with position absolute and with IE 6 . Thank you !