将多个浮动的div居中并排放置

3

我需要让三个

并排放置。因此,我创建了一个
,并在其中放置了三个
,CSS样式如下:

div.holder div {
  float: left;
  width: 250px;
  background-color: yellow;   

  /*margin-right:auto;  /**These did not help**/
  margin-left:auto;  */
}

And html like this:

<div class="holder">
  <div></div>
  <div></div>
  <div></div>
</div>

这应该是这样的:

three divs

但实际上,它看起来像这样:

three divs

div边框应与灰线的末尾对齐。


2
如果您想让您的“gold div”粘在右边,请将其设置为float: right - Brewal
@Brewal 这是一个好主意。如果您知道在中间放置银色元素的方法,那就太好了。也许我可以尝试使用 margin:auto - Tomáš Zato
1
以下线程正好有你要找的内容Fluid width with equally spaced DIVs - Itay
哦 - 对不起,我无法找到正确的查询来搜索。 - Tomáš Zato
3个回答

5
您正在为宽度指定像素值。无论您如何浮动,这些像素值都是固定的,永远不会到达边框的末端。您可以将宽度设置为百分比,例如width: 33%;。您还可以设置左右边距以分隔您的div,例如margin: 0 20px;
在这种情况下,我通常会将我的元素包装在一个div中,并使用该div来定位元素。然后,我会使用内部容器来设置背景颜色、文本颜色等。类似这样的东西可能适合您:
<div class="holder">
  <div class="wrapper">
     <div class="container">...</div>
  </div>
  <div class="wrapper">
     <div class="container">...</div>
  </div>
  <div class="wrapper">
     <div class="container">...</div>
  </div>
</div>

以下是相关的CSS代码:

.wrapper {
    float:left;
    width:33%;
}
.container {
    background-color: yellow;
    margin: 10px;
    padding: 20px;
}

这里有一个 fiddle: http://jsfiddle.net/bWFS8/

0

当我想要将div并排放置时,这就是我使用的方法:

CSS:

#menuitem {
font-weight:bold;
border-right-style:solid;
font-size:10.7px;
border-right-width:1px;
border-left-width:1px;
height:30px;
position:relative;
}

#menuitem span {
position:absolute;
text-align: center;
}

#menubar {
margin-top:10px;
position:absolute;
left:0px;
font-family:Verdana, Geneva, sans-serif;
}

HTML:

<div id="menubar">
<div style="float:left;width:104px;border-left-style:solid;" id="menuitem"><span style="bottom:9px;width:104px;">Menu Item 1</span></div>
<div style="float:left;overflow:hidden;width:78px;" id="menuitem"><span style="bottom:7px;width:78px;">Menu Item 2</span></div>
<div style="float:left;overflow:hidden;width:100px;" id="menuitem"><span style="bottom:9px;width:100px;">Menu Item 3</span></div>
</div>

希望我有所帮助。


0
如果您要将它们全部水平对齐,那么最好使用无序列表进行样式设置,使其显示为内联块,并使用zoom:1display:inline
没有理由使用浮动来将它们并排放置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接