Center Multiple DIVs with CSS

Center Multiple Divs with CSSAt some point, you may have a situation where you want to center multiple elements (maybe <div> elements, or other block elements) on a single line in a fixed-width area. Centering a single element in a fixed area is easy. Just add margin: auto and a fixed width to the element you want to center, and the margins will force the element to center.

There really should be a similar simple way to center multiple elements evenly spaced. It would be nice if CSS had a property called “box-align” which you could set to “center” then the child elements would be centered evenly within their parent.

Well, you can achieve something similar by taking advantage of CSS’s flexibity with “recasting” elements (for lack of a better term). View a demo of what I’ll be describing in this short tutorial.

The Usual Way

Normally, in such a situation, you would just float the boxes, then add left and right margins to space them out accordingly. But that can get a little messy, because IE6 doesn’t like margins on floats, and you always have to have a different id or class for elements on which you don’t want margins (like the last and/or the first).

You can get around the IE6 problem by adding display: inline in an IE6-only declaration, but your code will still be somewhat messy because of the extra code to get the first and/or last item to behave. Also, the last box could fall to the next line in IE.

There’s another solution to this that might work better in certain circumstances.

Use inline-block and control white space

To achieve the same effect as adding floats and margins, you can simply “recast” your block-level elements as inline blocks, and then manipulate the white space between them. Here is how the CSS might look:

#parent {
	width: 615px;
	border: solid 1px #aaa;
	text-align: center;
	font-size: 20px;
	letter-spacing: 35px;
	white-space: nowrap;
	line-height: 12px;
	overflow: hidden;
}

.child {
	width: 100px;
	height: 100px;
	border: solid 1px #ccc;
	display: inline-block;
	vertical-align: middle;
}

In my example above, I’m assuming there are four child boxes, each with the class child, and each 100 pixels by 100 pixels. The boxes are naturally block-level elements, but the CSS changes them to inline-block, which allows them to flow naturally with text and white space. Of course, since we don’t have any text in the parent container, controlling the text and white space will not be a problem.

The parent element (with the id parent in this example) has four key text properties set, and the children have two:

  • text-align makes all inline child elements centered
  • letter-spacing controls the size of each white space unit between boxes
  • white-space: nowrap keeps the last element from potentially dropping to the next line
  • overflow: hidden prevents the box from stretching in IE6
  • vertical-align: middle (on the children) keeps the boxes on the same vertical plane as each other when content is added
  • display: inline-block (obviously)

Internet Explorer Rears its Ugly Head

What would a CSS solution be without an Internet Explorer issue to work around? While this method works exactly the same in every browser (including IE8), IE6 and IE7 don’t cooperate, because they don’t fully support inline-block. To get those browsers to show virtually the same result, you need to add the following CSS:

.child {
	*display: inline;
	*margin: 0 20px 0 20px;
}

The CSS above must apply only to IE6 and IE7, and it has to appear after the other CSS. In my code (and in the code example above) I’ve accomplished this by using the star hack. The asterisk (or star) at the beginning of each line hides both lines from every browser except IE6 and IE7. The margins added here help us get the same visual result, and the new display property is taking advantage of a bug in those browsers that makes a block element work like its inline when you declare display: inline-block followed by display: inline.

Drawbacks / Final Thoughts

Not many drawbacks to this. You just have to make sure the white space and text settings that you apply are reset on any child elements inside the boxes. So, while this may work when you have straight images or other non-text content, it may be more trouble than it’s worth if your boxes are fully loaded with diverse content.

But nonetheless a good technique to know when you have to center some block elements with equal spacing, and you don’t want to apply extra classes on the end units. And this technique will be even more important when the older versions of IE disappear from general use. But I’m not holding my breath.

Advertise Here

59 Responses

  1. I think only margin : auto will not work for aligning it into center. You need to add margin : 0 auto;
    Am I wrong.. because I use it like this only and it works in all the browsers.

    • Yes, I do the same thing, but the zero value has nothing to do with the centering, it just keeps the top and bottom margins at zero. Technically, when you declare “margin: 0 auto” you’re basically just declaring shorthand for:

      margin-top: 0;
      margin-right: auto;
      margin-bottom: 0;
      margin-left: auto;
      

      I was just speaking briefly in the article, but yeah, I do “margin: 0 auto;” as well.

  2. Louis,

    I’m not worthy!! Thanks for this incredible post. I’ve been wondering about the properties of centering multiple divs for quite some time. Do you know if there is anything within the CSS3 specs that speaks to this as well?

  3. Nice approach. I like the idea of using letter-spacing attribute as margin between block elements. I often wrapped all elements into a box and used margin: 0 auto to center them, but it needed extra mark-up. Your solution is really good.

    Thanks for sharing.

  4. Oh I needed this! Thank you! CSS tips are my motivation to be creative!!

  5. Nice one, many thx ! :-D

  6. I hate the fact that we have to bow to the ineptitude of ie but there is just no other solution… Is there any wonder that MS attracts 98% of all virus’?

  7. My Horizontally centered menus method can be used to center any block-level elements in a cross-browser way, plus it does not rely on the inline-block rule: http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support

    • That’s a great technique, Matthew. You explained it very well, too, including some minor potential issues that could occur. I’m just wondering how much of a hindrance it would be to not be able to style the <ul> element. I suppose you could just use the wrapper, but if you wanted the styling to be only as wide as the <ul>, then it might be a problem.

      Of course, I only took a quick look so maybe I’m wrong about what I’m saying.

      Thanks for sharing that.

      • Thanks for your comment, Louis. You’re right that the <ul> element cannot be styled because it has an off-set position but if you really needed to, you could just add another <div> wraper to the markup. Then the <div> would be offset and you could style the <ul> anyway you like!

        Love your site BTW :)

    • Martin Gartner:

      Hello Matthew,
      is it possible to adapt your “horizontally centered menu method” so that the menu is right aligned? I’m fiddling around with this problem since a few days now… without success.

  8. S.Y. Lin:

    This idea is awesome, thx a lot. :-D

  9. Rasmus:

    Great! Thx a lot!

  10. Great article, very helpful. Thanks for sharing!

  11. Without those IE 7 & 6 fixes, the whole internets would fail and Al Gore will have to reinvent the internets again.

  12. This is really nice hack to align the div’s in the center. Thanks for the info.

  13. suprsidr:

    Luckily html5 will finally make this simple with display:table and display:table-cell… eventually 2022?

    -s

  14. Hum, it’s a good idea. I’m gonna try!
    Thank you!

  15. Thanks, nice article for css centering.

  16. It is possible to mimic this in IE6, using zoom and inline.
    This article contains a few different demos:
    http://tjkdesign.com/articles/how_to_style_thumbnail_and_caption.asp

  17. foxyd:

    Hi – That’s a great technique, but I couldn’t get it to work using Dreamweaver CS4 design view, then I hit the live button and the boxes all aligned perfectly. Any idea why CS4 renders the boxes vertically? If you are using Dreamweaver it would be a pain to not see the layout.

  18. Yura:

    boo:
    whitewhite-space: nowrap;

    • That’s a bug in the code highlighter. I can’t prevent that. Some CSS properties get messed up like that. If you click the “view plain” button, you’ll see that the raw code is correct

      I will eventually update the code highlighter, but I like the way this one looks as compared to the updates, so that’s held me back from changing it.

  19. Marcus Tucker:

    I’ve spotted a typo – your CSS includes the line:
    whitewhite-space: nowrap;

    Which presumably should be:
    white-space: nowrap;

  20. Robson Sobral:

    Great idea! Really great! But I found an issue: word-spacing! If you want to reset the word-spacing try “word-spacing: -.25em;”

  21. Awesome! Just awesome!

  22. Here’s another way to center multiple divs.

    http://2slick.com/div_center.html

    Just look at the simple source code of the page to how it’s done.

    Thanks,

  23. Wow I just found the same tutorial here…[link removed] … like every word too.

    Thanks for sharing Louis!

    • Yeah, that’s very common. Not much I can do to stop it. They’re wasting their time anyhow, because they’re not going to get any SEO value from that. I removed the link from your comment, though, because I don’t want to give them any exposure.

  24. That works in IE6, until you place some content inside each DIV, then it gets a mess-up.
    Example:

    A
    B

    C
    D

    Center them as explained here, it will not work… any idea? I haven’t found a solution yet. Thanks.

    • The html tag I put didn’t show, anyway, using the code shown in this article, just add some UL lists to the child div, then it will not work. That’s what I need to do now, any helps is appreciated. Thanks.

    • I’d have to see the code to see what the problem is. You’ll notice in the article, it says:

      You just have to make sure the white space and text settings that you apply are reset on any child elements inside the boxes.

      So, you might have to fix that by putting the white-space or other settings back to normal for the child elements.

  25. Rahi:

    Thanks, I really needed that.

  26. Josh:

    Nice and simple man. Worked great!

    Gonna use it everywhere.

    P.s. 5 seconds away from posting about the “whitewhite” typo, thankfully I scrolled slow enough to see the other comments on it :)

    Cheers,

    Josh

    • Actually, I realized in later posts that I can avoid that if I just change the “css” syntax label to “html”. So I did that now, and it looks fine.

      It won’t have the same color coding as real CSS, but it avoids that dumb duplicate text thing. Thanks for the reminder, because I have corrected this in later posts, but not in this one.

  27. Impressive.
    One need to be brave enough to mess with css typography in order to get this effect, I’m sure I’m not.

  28. Worked for me thanks. I wonder what the total cost is of wasted effort for ‘ie6-proofing’ websites. It must literally be in the millions.

  29. redman:

    superb, fantastic. Google led me here after smashing my head with alcohol!!

  30. Dave:

    The “display: inline;” attribute did exactly what I wanted. Thanks!

  31. von:

    it worked in a great way, specially i IE 6…
    thanks a lot for this tutorial…

  32. pal:

    its really very cool, i forgot this concept, after reading your article i am re-collecting my knowledge.

    Thank you so much

  33. Azamat:

    Hi! Thanx for this! But is there a way to make elements float, so that on wider screens elements below will go to the upper row and on small screens – will go down to the next row? Also it will be great to use spacing between blocks in “percents” for better adaptation to different screens.. Is there a solution to this?

    • I’m not sure what you mean by “float”, but you can definitely use percentages for the widths and the spacing, and then it will adapt to different screens. Just remove the fixed width on the parent and the child boxes.

      • Azamat:

        Thank you for the quick reply! Well, in fact fixed width of blocks is fine, By floating I mean that I want to use many blocks (like thumbnails) on a page without breaking them into groups of rows manually, rather let get organizing depending on the browser’s window width (responsive layout).. And in this case I want spacing between blocks set in percents.. Now it looks like the spacing in your example is set by “letter-spacing” which is in “px”, changing this value to percentage, like “5%” doesn’t work..

        • Well, you have to make sure that everything, including the parent and the child widths are in percentages. Then they will flex to fit, based on the width of the container.

          You can’t have any fixed widths in there, otherwise it will mess it up. When I get a chance, I’ll try to mock something up, but I don’t have time at the moment.

  34. Thanx , i was wondring how i can center an objet in css3 .

  35. Chelsea:

    Thank you so much! Saved me a looooooooooooooong night of fiddling with decimal ems!

  36. XCoder:

    Thanks :D

  37. Melissa:

    Hi!

    Thanks, this is great!

    I have used your code to nicely space my divs but in doing so I have lost the responsive ability to
    stack them when my screen is made smaller.

    Is there any way to have them nicely spaced but still able to be responsive and stack on top of each other
    when the screen is made smaller?

    Thank you!

  38. Ignat:

    amazing! Thanks a lot !

  39. will this work on responsive websites to? Ex . the end result will be the four boxes in a row but on a screen such as a smartphone will it stack on each other?

    • Yes, but you have to change the CSS using media queries. You have to remove the width on the parent element, and remove the overflow. That should do what you want.

      • candice:

        i input my code and I still have the data going down vertically

        • candice:


          .square
          {
          width: 100px;
          height: 100px;
          display: inline-block;
          vertical-align: center;

          }
          .container
          {
          width: 100%;
          text-align: center;
          /*font-size: 20px;*/
          /*letter-spacing: px; */
          white-space: nowrap;
          line-height: 12px;
          overflow: hidden;
          }
          my css

          • You’re going to have to create a demo that I can look at. I can’t debug code on a comment system. Use JSBin.com or CodePen.com to create a demo.

            Thanks.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field. If you use keywords, your comment will be deleted, or your name will be replaced with the alias from your email address. No foul language, please. Thank you for cooperating.

Instructions for code snippets: Wrap inline code in <code> tags; wrap blocks of code in <pre> and <code> tags. When you want your HTML to display on the page in a code snippet inside of <code> tags, make sure you use &lt; and &gt; instead of < and >, otherwise your code will be eaten by pink unicorns.