在一个 div 内居中一个宽度未知的 div

3
我有一个包含一个div元素的包装器,该div元素又包含了一些div。这些div在运行时会被添加或删除。HTML和CSS如下所示:
​<div id="Wrapper">
   <div class="InnerGreen">
       <div class="InnerContent"></div>
       <div class="InnerContent"></div>
   </div>    
</div>

​#Wrapper{
     width:600px;
     height:50px;  
     margin:10px 20px;    
     background:blue;}

.InnerGreen{
     background:green;
     margin:10px auto; // this doesn't center
     overflow:hidden;
     display:inline-block;}

.InnerContent{
     background:yellow;
     height:30px;
     width:40px;
     float:left;
     margin:3px 5px;}

我正在使用inline-block.InnerGreen包裹在Wrapper中,但是margin:auto似乎无法水平居中div。当然,如果我定义了.InnerGreen的宽度,这个方法是行得通的,但实际上.InnerContent divs是各种不同尺寸的div的集合,所以我无法在运行时设置.InnerGreen的宽度。
如何使margin:auto起作用?这里是jsfiddle
感谢您的建议。
4个回答

7

行内元素没有边距。通过将.InnerGreen设置为inline-block,您实际上是告诉它在定位方面表现为行内元素。另一方面,您仍然可以使用text-align将其居中:

#Wrapper {
    text-align: center;
}

请参见更新的JSFiddle


InnerContent divs不是文本:它们包含其他div。 - frenchie
@frenchie -- 没关系。它们是内联的,因此它们将作为内联位置,可以使用“text-align”居中。 - Roddy of the Frozen Peas

2

这可能不是技术上正确的做法,但你可以在包装 div 上放置 text-align:center


InnerContent divs不是文本:它们包含其他div。 - frenchie
@frenchie - 但是因为它们作为内联元素,你可以像处理文本一样对它们进行样式设置...例如使用 text-align: center - Roddy of the Frozen Peas

0
据我所知,在无法确定元素宽度的情况下,您无法使用margin:auto方法。虽然不是很优雅,但您可以通过居中表格来实现这一点:
<center>
   <table>
    <tr><td align="center">
       <div>This will be centered.</div>
    </td></tr>
   </table>
</center>

使用您的代码: http://jsfiddle.net/MaxPRafferty/yA7Nm/

0
你可以使用jQuery将div居中,类似于以下代码...
<script type="text/javascript">

    $(function() {
        var containerWidth = $(".InnerGreen").width();
        $(".InnerGreen).css("width", containerWidth);
    });
</script>

你的CSS设置应该就可以完成其余部分。

如果你在运行时添加内部内容,你可能还想在你的样式中添加height: auto,这将更好地控制元素的增长。


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