CodeinWP CodeinWP

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 are a number of old methods to center multiple divs, but this is now much easier to do using modern CSS techniques. I’ll cover the older methods in subsequent sections, but the easiest way to do this is shown first.

Center Multiple Divs with Flexbox

Flexbox is now one of the standards for dealing with layout techniques. The easiest way to center multiple divs is by putting them inside a flex container, then using a few flexbox features. Suppose we have the following HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

The following CSS will center the elements inside the container:

.container {
  display: flex;
  justify-content: center;
}

This centers the items with remaining space delegated to the left and right. If you want an equal amount of space between the items, you can do the following:

.container {
  display: flex;
  justify-content: space-between;
}

If you also want the same amount of space on the left and right, you can do this:

.container {
  display: flex;
  justify-content: space-around;
}

Of course, flexbox has so many more capabilities so if you want a full guide to using all the features of flexbox, I wrote a full flexbox tutorial that you’ll want to check out.

Below is an interactive demo that shows what the different values for justify-content do, so you can determine which one is best for your use case.

See the Pen
Aligning Elements Along the Main Axis: justify-content
by Louis Lazaris (@impressivewebs)
on CodePen.

If you want to learn how to center multiple divs using older methods, you can read the rest of this article which is basically the same older content that has appeared in this post for years.

The Old Way to Center Multiple Divs

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 using this technique to center multiple divs. 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.

70 Responses

  1. abhishek says:

    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. Queative says:

    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. rilwis says:

    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. Scott Corgan says:

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

  5. Webouriffant says:

    Nice one, many thx ! :-D

  6. Kevin Mist says:

    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 says:

      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 says:

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

  9. Rasmus says:

    Great! Thx a lot!

  10. Ted Thompson says:

    Great article, very helpful. Thanks for sharing!

  11. Jae Xavier says:

    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 says:

    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 says:

    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 says:

    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 says:

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

    Which presumably should be:
    white-space: nowrap;

  20. Robson Sobral says:

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

  21. Chris says:

    Awesome! Just awesome!

  22. angelo says:

    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. Chris says:

    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. Nestor Sulu says:

    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.

    • Nestor Sulu says:

      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 says:

    Thanks, I really needed that.

  26. Josh says:

    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. Derek says:

    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 says:

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

  30. Dave says:

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

  31. von says:

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

  32. pal says:

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

  33. Azamat says:

    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 says:

        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. Mounir says:

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

  35. Chelsea says:

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

  36. XCoder says:

    Thanks :D

  37. Melissa says:

    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 says:

    amazing! Thanks a lot !

  39. Candice says:

    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 says:

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

        • candice says:


          .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.

  40. raadif says:

    Thank you and love you

  41. Jordan says:

    Hi, this is great! It worked for what you described, but the problem is I need to center things on multiple lines. I need the site to be responsive also. See here: http://nothirdparty.com/home/

    I need it to be responsive, so the amount of divs on a line is constantly changing depending on browser size. You see that if you adjust the size of your browser, there will always be some awkward white space off to the right. This is the issue I’m trying to fix. Any ideas?

    • Jordan says:

      My previous comment was talking about the code I had before. I implemented your code. But now you can see…off to the right there are many more icons that are hidden. I need these to be displayed on the next line, and still everything should be centered. Any ideas?

      • Oh you did mention in the previous comment that there is awkward white space on the right, but that’s because of this:

        #main {
          max-width: 1175px;
          min-width: 250px;
        }
        

        If you add “margin: auto” there, it will center the #main element, but I don’t know if that’s what you want. Or maybe you already fixed the problem…?

    • Sorry for late reply, was on holiday…. Not sure I understand… I see 4 icons that are centered below the heading above, but on a wide monitor size, they don’t center, but neither does the heading.

      This is what I see:

      http://i.gyazo.com/1e9998cb58f9f52a8c55254394dd4c30.png

  42. Alvaro says:

    Great article, but what would happen if I need more than one row, if I use the white-spacing:nowrap attribute, it’s going to keep adding blocks, but they’re gonna remain hidden.

    • Yes, that’s correct, and that’s why it would be better to use something new like Flexbox for this, or else just don’t use “nowrap”, although that might have other undesirable effects.

  43. al3ab atfal says:

    If you add “margin: auto” there, it will center the #main element, but I don’t know if that’s what you want.

  44. Ravikumar V says:

    by giving Flexbox “display: flex; justify-content: space-evenly” we can achieve it, right ? just sharing my thought

  45. Terry Ferguson says:

    It worked for me. Great guide. Thanks a lot.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).