CSS清除float浮动的4种方法
2017-09-08 本文已影响119人
neromaycry

在开发网页的时候经常需要用到各种浮动,此时便需要及时的清除浮动,否则将会导致布局出现问题,所以本人在网上整理了一下CSS清除float浮动的各种方法,以下4种方法,本人亲测有效:
方法一:after伪元素(推荐)
废话不多说,直接上代码:
CSS:
.outer {
border: 1px solid black;
width: 300px;
position: relative;
}
.inner {
width: 50px;
height: 50px;
background-color: red;
margin-right: 20px;
float: left;
}
.footer {
background-color: blue;
width: 200px;
height: 100px;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden
}
HTML:
<div class="outer clearfix">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>
<div class="footer"></div>
方法二:使用额外标签法
CSS:
.outer {
border: 1px solid black;
width: 300px;
}
.inner {
width: 50px;
height: 50px;
background-color: #3b73b9;
margin-right: 20px;
float: left;
}
.footer {
background-color: #111f2c;
width: 200px;
height: 100px;
}
.clearfix {
clear: both;
}
HTML:
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="clearfix"></div>
</div>
<div class="footer"></div>
方法三:给父元素定高
CSS:
.outer {
border: 1px solid black;
width: 300px;
height: 50px;
}
.inner {
width: 50px;
height: 50px;
background-color: #3b73b9;
margin-right: 20px;
float: left;
}
.footer {
background-color: #111f2c;
width: 200px;
height: 100px;
}
HTML :
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>
<div class="footer"></div>
方法四:利用overflow:hidden属性
CSS:
.outer {
border: 1px solid black;
width: 300px;
overflow: hidden;
zoom: 1;
/*兼容 IE*/
}
.inner {
width: 50px;
height: 50px;
background-color: #3b73b9;
margin-right: 20px;
float: left;
}
.footer {
background-color: #111f2c;
width: 200px;
height: 100px;
}
HTML:
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>
<div class="footer"></div>