Div horizontal centering when there’s more than one of it

We know about margin: 0 auto; that will center a div horizontally. It works by setting up an equal left and right margin to the div. But I never find an easy way to do this when there’re 2 or more consecutive divs on the “same line” because:

  • Using margin auto will push the next div below, as they are still considered as block level elements.
  • We can use floats to put the divs on the same line, but we can’t center a float.
  • Using: position: absoluteleft: 50%margin-left: (minus of half of the element’s width), is too complex if there’re a lot of divs. And it’s also impossible (without complex JavaScript) if the elements’ widths are relative.
  • We don’t want to use tables.
  • Etc.

I often found the need to do this when I’m going to create a horizontally centered main menu, while the menu items needs to be displayed in block to make it work with nice rollovers, complex dropdowns, and the likes, while the parent main menu items needs to be on relative width.

This is the simplest way I know to solve the problem. Sadly it still involves a little JavaScript (I’ll be using jQuery):

The divs are centered
The divs are centered
  1. Float the block-level inner items (teh red boxes) to the left.
  2. Wrap it with an absolute positioned container (the blue box). Set the top attribute.
  3. Wrap it again with a relative positioned container (the green box).
  4. Use JavaScript to set the absolute positioned container’s (the blue box) margin-left, and left.

The divs are now horizontally centered. People without JavaScript will see the main menu nicely (including complex rollovers etc) except for the horizontal centering.

And although I personally have dropped support for IE6, this method works on it.


Do you have a better solution? I’d be very grateful if you share it with me, thanks before 🙂

Leave a Reply

Your email address will not be published.