自动高度父级的100%高度子div

时间:2011-08-21 06:40:37

标签: css html css-float

在过去的几个小时里,我一直在网上寻找我的问题的答案。我阅读了关于alistapart的Floats 101文章以及关于stackoverflow的大量类似问题。我想最后我问的问题是防止我的脑袋爆炸。

我试图做的事情: 具有固定宽度的容器包含100%宽度的div,其具有两个子节点。 div垂直扩展到其中的内容。这两个子元素在父div中形成列,因此浮动以将它们并排放置。左列扩展到父div的高度并具有背景颜色。右列没有背景颜色,并确定父div的高度。

这很难解释所以我试图创建一个例子: http://jsfiddle.net/bituser/LzNuN/1/

我真的很感谢你的帮助。感谢

2 个答案:

答案 0 :(得分:6)

根本不要浮动右列,只要给它足够大的余量以容纳左列。浮动元素将从正常文档流中删除,并且不会对其父级的高度做出任何贡献;所以,如果你同时浮动左右两列,你的红色#box元素最终没有高度,你看不到它;如果你停止浮动右列,那么它确实会确定#box的高度。如果您根本不浮动#right_column,那么它将展开以使用#box中的所有可用宽度。

这样的事情:

<div id="container">
    <div id="box">
        <div id="left_column">
            <p>details stuff yada yada yada</p>
        </div>
        <div id="right_column">
            <p>other stuff yada yada yada test test test test test stuff stuff content content content content content stuff stuff example stuff test stuff content content stuff content example</p>
        </div>
    </div>
</div>

CSS:

#container {
    width: 400px;
}
#box {
    background-color: red;
}
#left_column {
    width: 200px;
    background-color: blue;
    float: left;
}
#right_column{
    margin: 0 0 0 200px;
    background-color: green;
}

更新了小提琴:http://jsfiddle.net/ambiguous/eDTdQ/

或者,您可以向width: 200px添加#right_column并让其保持浮动状态,然后将overflow: hidden添加到#box,以便#box展开以包含其漂浮的孩子们:

#box {
    background-color: red;
    overflow: hidden;
}
#right_column{
    background-color: green;
    float: left;
    width: 200px;
}

此方法的实时版本:http://jsfiddle.net/ambiguous/eDTdQ/2/

如果您希望右列自动拉伸,并且您希望两列都是全高,那么您绝对可以放置左列而不是浮动它:

#box {
    background-color: red;
    position: relative;
}
#left_column {
    width: 200px;
    background-color: blue;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
}

直播:http://jsfiddle.net/ambiguous/3Cxe3/

答案 1 :(得分:1)

看看这个:http://jsfiddle.net/LzNuN/3/ 你需要在总宽度上添加边距 - 右边的边距左边不是父节点的左边距左边边距左边边距所以如果你的总边距是400px而你的左边是200px你右边的列也是200px,没有余地的空间

相关问题