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.
- We don’t want to use tables.
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.
- Float the block-level inner items (teh red boxes) to the left.
- Wrap it with an absolute positioned container (the blue box). Set the top attribute.
- Wrap it again with a relative positioned container (the green box).
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 🙂