使子div扩展以填充父div的宽度

时间:2013-07-19 23:41:19

标签: html css

所以我在一个div里面有三个div。

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

我希望子div填充父级的宽度(子级的组合宽度应该是父级)。然而,这种情况并没有发生,我正在做空。我认为这是因为子div基于其内容设置宽度。

我如何实现我想要的目标?

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;

}

3 个答案:

答案 0 :(得分:9)

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

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

最后一行确保它在框中添加边框,填充和边距时也能正常工作。

ONLINE DEMO

Ps:没有直接关联但是父母的边框底部也有错误,在上面的小提示中得到纠正。当您使用非0值时,您需要指定单位:

    border-bottom:1px;

答案 1 :(得分:8)

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

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

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

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

答案 2 :(得分: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;
}