【问题标题】:Center any amount of divs inside a parent div with CSS使用 CSS 在父 div 中居中任意数量的 div
【发布时间】:2013-01-01 07:21:24
【问题描述】:

我有一个带有随机数量的子 div 的父 DIV(菜单栏)。我正在寻找一个干净、简单的 CSS,它将始终水平居中子 div,而不管它们的宽度或 div 的数量(只要它们适合父级)。我不想计算所有宽度或使用绝对定位。

在查看了几个解决方案后,我想出了这段代码,但是子 div 仍然不能正确居中,尤其是当你用文本或图像填充它们时。

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;
}

我创建了这个 JSFiddle 来说明我的问题:http://jsfiddle.net/mZ2P2/

【问题讨论】:

  • 那些对我来说正确(水平)居中。您的意思是它们应该垂直居中吗?

标签: css alignment center


【解决方案1】:

您忘记vertical-align 内联元素,以便它们在高度不同时正确显示。这是working example。我还删除了按钮的id 属性并将其更改为class

编辑: jsfiddle.net 现在对我来说不是很好。引入的更改是 vertical-align: top.button 类。

【讨论】:

  • 哇,这正是我所需要的。非常感谢!
【解决方案2】:

为什么不使用无序列表,然后使用 css 将它们定位在中心。

【讨论】:

  • 我需要水平居中,请参阅我添加的 JSFiddle。我可以使用无序列表来实现这一点吗?
  • 看看这个jsbin.com/avuhep/1/edit你可以根据需要编辑ul和li。
  • 对不起,我有点糊涂了..看起来有人已经给你答案了。
  • 据我所见,这仍然是垂直居中。上面的答案虽然有效。
猜你喜欢
  • 2014-08-31
  • 2013-05-22
  • 2016-02-29
  • 1970-01-01
  • 2018-02-17
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多