Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering Horizontal divs inside the outer Div?

Tags:

css

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.

like image 855
user481913 Avatar asked Dec 05 '25 11:12

user481913


1 Answers

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 */
}
  • DEMO

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 */;
}
  • DEMO

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

like image 153
calebds Avatar answered Dec 07 '25 16:12

calebds