清除浮动的几种方法

为父元素添加overflow:hidden

html标签(以下都以此为准):
<div class="parent">
<div class="child>
Hello World
</div>
</div>
<footer>Whatever</footer>
style写法:
.parent{
border:1px solid red;
overflow:hidden;
}
.child{
width:20px;
height:20px;
background:black;
float:left;
}

同时浮动父元素

父元素浮动后会收缩包裹子元素,所以根据需要设置父元素的宽度。
parent的浮动会强制使footer布局在parent旁边,因此要使用clear:left进行清除:
.parent{
float:left;
width:100%;
}
footer{
clear:left;
}

添加非浮动的清除元素

为父元素添加一个新类<div class="parent clearfix"></div>:
.clearfix:after {
content:".";
display:block;
height:0;
visibility:hidden;
clear:both;
}
如果要考虑兼容的话,可以在父元素下添加一个新的子元素并将样式写成clear:left;

没有父元素,在同级中清除方法同上

posted @ 2016-01-13 09:30  Json_cheeTsui  阅读(128)  评论(0编辑  收藏  举报