前言
- 为什么
使用浮动
?- 为什么要
清除浮动
?- 清楚浮动有几种
解决方案
?
浮动
-使用浮动是因为在
html
中有时候会遇到几个块元素并排的问题或行元素需要设置宽高或内外边距时,所以就会使用到浮动。
<body>
<ul>
<li class="list"></li>
<li class="list"></li>
<li class="list"></li>
<li class="clear"></li>
</ul>
</body>
为什么清除浮动
由上图可见,在浮动后父元素高度没有了,为了解决父元素高度塌陷的问题,我们就要用到清除浮动。
- 清除由于子元素浮动带来父元素高度塌陷的影响。
- 同级元素浮动后,会脱离文档流,对布局造成了影响,也要用到清除浮动。
给后边的兄弟元素添加
clear:left;
。
解决方案
ul{
border: solid blue 2px;
margin-top: 20px;
}
.list{
width: 100px;
height: 100px;
margin: 10px 20px;
float: left;
border: 2px solid #ccc;
background-color: rgb(233, 15, 15);
}
.clear{
clear: both;
overflow: hidden;
}
缺点:
要在页面添加许多冗余元素,太过于麻烦,而且不符合语义化。
//父级
ul {
border: solid blue 2px;
margin-top: 20px;
}
//父级类名,伪元素
.box:after {
content: "";
display: block;
line-height: 0;
visibility: hidden;
clear: both;
}
.list {
width: 100px;
height: 100px;
margin: 10px 20px;
float: left;
border: 2px solid #ccc;
background-color: rgb(233, 15, 15);
}
缺点:
IE6/IE7不识别:after伪元素,存在兼容性问题
缺点:
只适合高度固定的布局,要给出精确的高度,如果高度和父级div不一样时,会产生问题。对于响应式布局会有很大影响。
总结
float
的属性left
right
none
inherit
clear
的属性left
right
both
none
inherit