Kokodoko
Kokodoko

Reputation: 28158

Center any amount of divs inside a parent div with CSS

I have a parent DIV (a menu bar) with a random number of child divs. I'm looking for a clean, simple CSS that will always center the child divs horizontally, regardless of their width or the number of divs (as long as they fit inside the parent). I don't want to have to calculate all the widths or use absolute positioning.

After looking at several solutions I came up with this code, but the child divs still don't center properly, especially when you fill them with text or images.

HTML:

<div id="menubar">
   <div id="button">too much text will offset the other buttons</div>
   <div id="button">b2</div>
   <div id="button">b3</div>
</div>

CSS:

#menubar {
    position:absolute;
    bottom:0px;
    background-color: #00A0E2;
    width:100%; height:80px;
    text-align:center;
} 

#button {
    margin: 5px auto 5px auto;
    width:120px;height:70px;
    display:inline-block;
    background-color:white;
    cursor: pointer;
}

I have created this JSFiddle to illustrate my problem: http://jsfiddle.net/mZ2P2/

Upvotes: 0

Views: 1158

Answers (2)

You forgot to vertical-align the inline elements so that they display correctly when they do not have the same height. Here's a working example. I also removed the id attribute of your buttons and changed it for a class.

EDIT: jsfiddle.net is not working all that well for me right now. The change introduced was vertical-align: top to the .button class.

Upvotes: 2

Bazinga777
Bazinga777

Reputation: 5291

Why dont you use an unordered list and then use the css to position them in the center.

Upvotes: 0

Related Questions