user481913
user481913

Reputation: 1018

Centering Horizontal divs inside the outer Div?

I'm creating a horizontal menu bar.

There is an outer div that contains inner divs (each of these divs is the individual menu item).

I use float: left for styling on these inner divs to display them horizontally instead of vertically.

The problem is that the menu bar has uneven space on the left and right, hence the overall menu bar doesn't appear to be centralized... i.e the first menu item on left has lesser space from left border and the space between last menu item on right and the right border is more.

I want equal margin/padding on the left and right to make the menu bar display in center.

I tried setting margin-left: auto; margin-right: auto on the outer div and then on the inner div as well. Both don't seem to help.

Already had a look here: How to horizontally center a <div> in another <div>?

However this particular answer is to center just one div, what I have is a collection of horizontal divs (menu items) that need to be centralized.

Any help is appreciated.

Upvotes: 3

Views: 8717

Answers (2)

calebds
calebds

Reputation: 26228

If your menu items aren't complex (like no fixed sizes or sub-elements), try adding the following styles:

#outer {
    text-align: center;
}
.menu-item {
    display: inline; /* replace 'float:left' with this */
}

Otherwise you'll need a wrapper for the inner elements that has a fixed width:

#wrapper {
    margin: 0 auto; /* center in outer DIV */
    width: /* sum of widths of inner elements */;
}

NOTE: Semantically its better to style menu items using a list, as in the DEMOs.

Upvotes: 3

Abhranil Das
Abhranil Das

Reputation: 5918

Firstly if all your menu items have specified widths and display:inline which is default, you wouldn't need a float to line them up.

But supposing you do, when you set a float, your elements are removed from the natural flow of the document, and hence margin:auto will not work to center it. What you could do in this case is create another container div of specified width for the menu items, within which you could use float to line them up. Now what's left is to center this one container div within your outer div, which you have already seen how to solve. For example, you could use the margin:auto technique on the container div to center it. Make sure you have text-align:center for the outer div.

Upvotes: 1

Related Questions