2013-07-19 174 views
8

所以我有一个div内的三个div。让子div扩展为填充父div的宽度

<div class="parent"> 
<div class="child> Text</div> 
<div class="child">Text</div> 
<div class="child">Text</div> 
</div> 

我想让孩子的div填满家长的宽度(孩子的总宽度应该是父母)。但是,这并没有发生,我倒下了。我认为这是因为孩子divs根据他们的内容设置宽度。

我该如何实现我想要的?

CSS-

.child { 
    background: white; 
    color: #a7a9ac; 
    cursor: pointer; 
    font-size: 15px; 
    border-right: 1px; 
    border-top: 0; 
    border-bottom: 0; 
    border-left: 0; 
    border-style: solid; 
    border-color: @faded-grey; 
    padding-right: 10px; 
    margin: 0 auto; 
    height: 100%; 
} 

.parent { 
    border-top: 1px; 
    border-left: 0; 
    border-bottom: 1; 
    border-style: solid; 
    border-color: @faded-grey; 
    border-right: 0; 
    width: 100%; 
    margin-right: 0px; 
    height: 80px; 

} 
+0

你可以发布你正在使用的CSS? – cr0atIAN

+0

有很多方法,但这取决于你想要什么。在内容确定宽度后,是否希望_last_子div填充剩余空间?或者你想让它们均匀分布,_i.e._通过'width:33%'? –

+0

设置CSS,尝试宽度:33%,但它将div放在另一个上面 – praks5432

回答

8

如果你知道总会有三个孩子,你可以简单地使用:

.parent > .child { 
    float: left; 
    width: 33%; 
} 

.parent { 
    overflow: auto; /*or whatever float wrapping technique you want to use*/ 
} 

如果你不知道有多少孩子有,你需要使用CSS表格,flexbox,或者可能将内联块与text-align:justify组合在一起。

8

可以这三个属性添加到.child CSS规则:

width:33%; 
float:left;  
box-sizing: border-box; 

最后一行确保当您添加边框,填充和利润率在箱子上它也将正常工作。

ONLINE DEMO

PS:没有直接关系,但也有在边框底部为父母,在拨弄上述纠正的错误。当您使用非0值需要指定单位:

border-bottom:1px; 
+0

'box-sizing:border-box' is magic!非常感谢。 –

+1

棒极了!尊重其他答案,我认为这是最好的答案。 – Phil

+0

使中间宽度为34%,否则只填充99%的容器。 – Sami

6

我需要为我的解决方案,以适应元素的数量变化对他们来说是完全响应。

我发现了一个有趣的解决方案。它基本上显示为一张表格。可用的每一个元素股宽度,这也适用于图像非常好: http://jsfiddle.net/8Qa72/6/

.table { 
    display: table; 
    width: 400px; 
} 

.table .row { 
    display: table-row; 
} 

.table .row .cell { 
    display: table-cell; 
    padding: 5px; 
} 

.table .row .cell .contents { 
    background: #444; 
    width: 100%; 
    height: 75px; 
} 
+1

另一个有趣的解决方案是使用'display:inline-block'试试它,它有时可以挽救生命;-) –

+0

如何?它不会在孩子之间平均分配父母的可用宽度。你可以在JSFiddle中显示我吗? –

+0

你说得对,如果你想要类似的东西,你必须指定每个孩子的父div的百分比 我尝试了“动态”接近和“固定”接近 http://jsfiddle.net/dBeNv/40/ –