问题:

<div>
    <div style=\"float: left;\">Div 1</div>
    <div style=\"float: left;\">Div 2</div>
</div>

在上面代码中的父div 不会扩大到包含其浮动的孩子 - 它会显示有height: 0

 

解决办法一:

使用.clearfix::after

代码如下:

HTML:

<div class=\"clearfix\">
    <div style=\"float: left;\">Div 1</div>
    <div style=\"float: left;\">Div 2</div>
</div>​

CSS:

.clearfix::after { 
   content: \" \";
   display: block; 
   height: 0; 
   clear: both;
}

 

解决方法二:

也可以设置display: inline-block;width: 100%;模拟正常的块元素,而不是折叠。

.clearfix {
    display: inline-block;
    width: 100%;
}

这个解决方案应该向后兼容IE5.5,但只在IE6中测试过

 

解决方案三

将父母设置为overflow: auto

<div style=\"overflow: auto;\">
    <div style=\"float: left;\">Div 1</div>
    <div style=\"float: left;\">Div 2</div>        
</div>

 

解决方案四

在父元素内附加一个“spacer”元素,如下所示:

<div>
    <div style=\"float: left;\">Div 1</div>
    <div style=\"float: left;\">Div 2</div>
    <div class=\"spacer\" style=\"clear: both;\"></div>
</div>    
收藏 打印