Center any amount of divs inside a parent div with CSS

穿精又带淫゛_ 提交于 2020-01-06 21:05:16

问题


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/


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/14384407/center-any-amount-of-divs-inside-a-parent-div-with-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!