MicroTut: Centering a Div Both Horizontally And Vertically

MicroTut: Centering a Div Both Horizontally And Vertically

While building web page layouts, you’ve probably been faced with a situation where you need to center a div both horizontally and vertically with pure CSS. There are more than a few ways to achieve this, and in this MicroTut I am going to show you my favorite involving CSS and jQuery.

But first, the basics:

Horizontal centering with CSS

It is as easy as applying a margin to a div:

.className{
	margin:0 auto;
	width:200px;
	height:200px;
}

To center a div only horizontally, you need to specify a width, and an auto value for the left and right margins (you do remember the shorthand declarations in CSS don’t you?). This method works on block level elements (divs, paragraphs, h1, etc). To apply it to inline elements (like hyperlinks and images), you need to apply one additional rule – display:block.

Horizontal and vertical centering with CSS

Center a div both horizontally and vertically with CSS is a bit more tricky. You need to know the dimensions of the div beforehand.

.className{
	width:300px;
	height:200px;
	position:absolute;
	left:50%;
	top:50%;
	margin:-100px 0 0 -150px;
}

By positioning the element absolutely, we can detach it from its surroundings and specify its position in relation to the browser window. Offsetting the div by 50% from the left and the top part of the window, you have its upper-left corner precisely at the center of the page. The only thing we are left to do is to move the div to the left and to the top with half its width and height with a negative margin, to have it perfectly centered.

Horizontal and vertical centering with jQuery

As mentioned earlier – the CSS method only works with divs with fixed dimensions. This is where jQuery comes into play:

$(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();

The functionality is inserted into a $(window).resize() statement, which is executed every time the window is resized by the user. We use outerWidth() and outerHeight(), because unlike from the regular width() and height(), they add the padding and the border width to the returned size. Lastly, we simulate a resize event to kick center the div on page load.

The benefit of using this method, is that you do not need to know how big the div is. The main disadvantage is that it will only work with JavaScript turned on. This however makes it perfect for rich user interfaces (such as facebook’s).

Be sure to share your favorite methods in the comment section.

Join our newsletter and get our PSDs!18,457 people learn about HTML5, JS and more. Join them!

by Martin Angelov

Martin is a web developer with an eye for design from Bulgaria. He founded Tutorialzine in 2009 and it still is his favorite side project.

46 Comments

  1. David says:

    Loving the new Micro Tuts section. Keep up the good work! :)

  2. Cool concept, looking forward to more Micro Tuts.

  3. John says:

    Nice tut! Loving how this is achievable in both CSS and jQuery so that you're not boxing yourself into one solution.

    I want to see more like these! :)

  4. Except that you *can* center things both horizontally and vertically using just CSS, and without knowing the container's size:

    http://benalman.com/code/test/css-centering.html

    (the jQuery used in this example is to simply show that you don't need to know the size of the element to keep it centered)

    - Ben

    1. Thanks for the tip, Ben! It really helped a lot to finish a project I was working on.

  5. Martin Angelov says:

    Thanks for the comments fellas!

    @ "Cowboy" Ben Alman

    Interesting experiment. Kinda too hackish for me but there you have it - centering a div with css IS possible without knowing its size.

  6. Thanks for vertical centering tut!

  7. Lam Nguyen says:

    Hi Martin, I'm fan of your MicroTut section now. It's very helpful. You are doing a good job, friend!

  8. Parag says:

    Great example Martin. One thing i noticed about this example is that when there is a vertical scroll on the page the element is centered to the position of the whole document. This can be fixed easily by replacing the document with window like:

    left: ($(window).width() - $('.className').outerWidth())/2,
    top: ($(window).height() - $('.className').outerHeight())/2

  9. Stephane says:

    Micro Tuts section is a great idea, Always interesting to discover new css techniques.

  10. Martin Angelov says:

    @ Parag

    Thank you for noticing that! I fixed it in both the article and the demonstration.

    For those of you reading this comment, I had wrongly used $(document).width() and $(document).height() instead of $(window).width() and $(window).height().

    The difference is that the $(document) methods return the size of the entire document, and the $(window) ones return only the dimensions of the browser window (the document can expand way beyond the browser window).

    The example pages didn't have content which overflowed outside of the window, so the error went unnoticed.

  11. I prefer the jquery workaround .

  12. Adrian says:

    This is an cool tut. Very useful ! Thank`s a lot, i know for sure that i`l use this on few websites!

  13. Tyron Bache says:

    Brilliant, just what I've always wanted! Thanks to @smashingmag

  14. Joe Hana says:

    Great micro tut :-)

    however, i use a more dynamic solution for the second example. instead of giving the div a fix width and height and taking the half of the values as negative margin, i'm used to giving the div a % width, lets say: 20%
    and a position: absolute; with left: 40%;.

    Its quite the same...

    thanks again :-) and keep up the good work

  15. Maverick says:

    that's a neat little tut.

    want more :)

  16. I love this site! Very good tutorial laying out the differences between the two methods. I think, like most, that jQuery is the easiest solution but having to account for those 5% that don't have scripting turned on can be frustrating.

  17. Jucca says:

    Great tutorial, tks!
    I suggest in this section, a tutorial about how create equal height columns. I google a solution, but not the best.
    Congratulations.

  18. durgesh says:

    can i use your demos in my website?

  19. All your tuts are awesome...i like very much..Explanation is very understandable...Keep on...........

  20. Peter says:

    Just what I was looking for. Thanks! :)

  21. bnibbler says:

    Those "microtuts" are excellent!
    thanks a lot for those simple and useful tips.

    Keep them comming!

  22. Alen says:

    Cool. Nice and simple solution.

  23. Sergi says:

    This is just awsome. Have been using such painful solutions for months. Yours are clear, simple and perfect. Thank you so much.

  24. pa says:

    I love these super handy tiny tuts, it's like a band aid for the brain just when you need it.

  25. Anuj says:

    Simple and to the point tutorial.. Thank for clearing the concepts.

  26. geert says:

    There is a little problem with this solution when the browser window is smaller than the content to be centered. If you rezise the browser to a height smaller than the centered content, a vertical scrollbar appears. That's good, but you can not reach the top of the content again. This problem is in all major browers...

    1. Nicholas says:

      Yeah! I've noticed this too. It can be a really bad problem when it comes to people's browsers full of toolbars, like my client's IE7. Yeah I know, this sucks, but what am I going to do if they like to use 1/4 of the window to see the content =P

      I'm searching for some workaround that account's this problem, so when the window is smaller than the content it should snap to the top of the content. Does someone know how to do this?

  27. james says:

    when I initially open my my page the content is not centered then when I go and change the size of the window it snaps to the perfect spot int the center. I copied the code exactly... I am not sure why the $(window).resize(); dosent initially get the detentions... Should I place that higher in my document?

    1. Olivia says:

      I am having this same issue...

      1. Nolan says:

        did you guys ever figure out a solution to this? mine works but only after you resize the window.

        1. Jeff says:

          I am also having this issue since I believe its because the function is on resize... since we havn't resized anything yet it takes the first time to actually run the function...

          wondering if anyone has found a fix

        2. Geoff says:

          This solution works for me, simply add "onLoad="$(window).resize()" to your <body> tag.

          Ex:
          <body onLoad="$(window).resize()">

          1. Nick Meagher says:

            This didn't really fix the problem, when you hard refresh (shift + refresh) its still having the same issue. Has anyone found a fix for this?

  28. Bjornio says:

    mate, that was handy! Thanks alot

  29. Johnny says:

    There's a simple yet great jQuery plugin to center your content vertically and horizontally:
    link

  30. Sagar says:

    Perfectly worked for me..really nice tutorial..thank u very much.

  31. Dex Barrett says:

    I did a quick test to check the horizontal centering and it worked in FF and Chrome but it didn't work in IE (i have version 9). I didn't know you have to specify a Doctype so that it works in IE.

  32. Bob says:

    This seems to work fine: position:absolute;left:50%;top:50%;margin:auto

  33. Linas says:

    Works like a charm with jQuery.

  34. The second example with CSS works like a charm!
    Thank you!

  35. Josh says:

    See example here. Note it is only out by about 20px or so vertically http://phocks.org/words/dream/

  36. Linas says:

    Thanks, finally this annoying thing is done properly!

  37. Anthony Lee says:

    Great way to do in javascript!

  38. Marty says:

    struggled with this so long. i never thought about using negative margin to center the element - great work :)

Add Comment

Add a Reply

HTML is escaped automatically. Surround code blocks with <pre></pre> for readability.
Perks:   **bold**   __italics__   [some text](http://example.com) for links