【面试日记】CSS清除浮动

99 阅读1分钟

清除浮动其实就是解决父元素塌陷的问题,这里简单记录一下解决办法

先来一个经典办法

//html
<div class="father">
    <div class="child"></div>
</div>

//css
.father:after{
    content:"";
    display:block;
    height:0;
    visiblity:hidden;
    clear:botn;
}
.father{
    *zoom:1//*ie6清除浮动的方式 *号只有IE6-IE7执行,其他浏览器不执行
}

反手再来一个

//html
<div class="father">
    <div class="child"></div>
</div>

//css
.father:after,.father:before{
    content:"";
    display:block;
}
.father:after{
    clear:botn;
}
.father{
    *zoom:1//*ie6清除浮动的方式 *号只有IE6-IE7执行,其他浏览器不执行
}

为了面试可能会问你四种办法,所以再给两种不是很好的办法,看看就行

//加一个空元素,添加clear:both清除浮动
//html
<div class="father">
    <div class="child"></div>
    <div class="clear"></div>
</div>

//css
.clear{
    clear:both
}

//给父元素添加overflow:hidden
//html
<div class="father">
    <div class="child"></div>
</div>

//css
.father{
    overflow:hidden;
}