CSS父子高度

时间:2009-10-26 17:21:24

标签: css height parent

我对这些代码段有一些问题:

CSS:

#wrapper{
    width: 600px;
    background: gray;
}

#left{
    float: left;
    width: 150px;
    height: 80px;
    background: red;
}

#right{
    float: left;
    width: 450px;
    height: 150px;
    background: yellow;
}

HTML:

<div id="wrapper">
    <div id="left"></div>
    <div id="right"></div>
</div>

左边的高度是80px,右边的高度是150px。我希望这件事看起来像这样: http://img408.imageshack.us/img408/9978/dream.th.jpg 以上来自IE的截图,当我使用IE时,这些片段工作得非常完美。但是当我使用其他浏览器(opera,FF,Safari,Chrome)时,我得到了这个: http://img408.imageshack.us/img408/869/fact.th.jpg

这不酷...我希望父(#wrapper)元素的高度能够让两个孩子的身高更高。

6 个答案:

答案 0 :(得分:2)

CSS

#wrapper:after {
 visibility: hidden;
 display: block;
 font-size: 0;
 content: " ";
 clear: both;
 height: 0;}

答案 1 :(得分:1)

这是IE中的一个错误。

Containing floats解释了为什么会看到这种行为,而Methods for Containing Floats提供了比添加额外标记更好的解决方案。

答案 2 :(得分:0)

感谢David的快速回答。我没有阅读你写的所有内容(两个链接),但我在第二个链接上遇到了一个解决方案。我放了一个额外的div,“清楚:两个;”到容器,它的工作!谢谢。 Matt Ball:谢谢,但我希望这个东西能够动态增长

答案 3 :(得分:0)

当两个div浮动在一个没有固定高度的容器中(或者它的高度小于所包含的div的最大高度)时,你的容器会在一行像素中折叠并浮动div(s)溢出容器。

要强制容器包含两个div,您需要在关闭容器之前清除两个浮点数! 换句话说......

CSS

<style>
#wrapper{
    width: 600px;
    background: gray;
}

#left{
    float: left;
    width: 150px;
    height: 80px;
    background: red;
}

#right{
    float: left;
    width: 450px;
    height: 150px;
    background: yellow;
}

.clearer{ clear: both;}
</style>

HTML

<div id="wrapper">
    <div id="left"></div>
    <div id="right"></div>
    <div class="clearer"></div>
</div>

答案 4 :(得分:0)

只需将父级的溢出样式设置为除可见之外的任何内容,它将环绕子内容。

答案 5 :(得分:0)

我发现的最佳解决方案类似于上面的Rodrigo,但不需要内容中的空格字符(因此也不需要指定字体大小)。如果你把它作为一个类,你可以将它应用于任何容器块,而不仅仅是你的包装器。 (我也觉得最好不要设置ID,但这是一个不同的问题。)

.clearfix:after {
    clear: both;
    content: "";
    display: block;
    height: 0;
    visibility: hidden;
}
*:first-child+html .clearfix { /* Optional fix for IE7 */
    zoom: 1; 
}