經常會遇到需要清除浮動的情況,總結了以下4種情況,以及各自的優缺點。
1、給父元素設置高度
這是一種最容易想到的方法,前提是需要知道子元素需要占用的高度(一般比較局限)
2、給父元素設置overflow:hidden
或者 overflow:auto
這個方法其實不好用,因為當你有元素需要 超出父元素的時候就不行了(曾經嘗試用絕對定位超出父元素,結果都不行)
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
</div>
css
.outer{
width: 200px;
background-color: #04b4ba;
overflow: auto; /*或者 overflow: hidden;*/
}
.inner{
width: 50px;
height: 50px;
background-color: red;
float: left;
}
3、采用clear: both;
(需要額外增加一個子元素)
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="clear"></div>
</div>
css
.outer{
width: 200px;
background-color: #04b4ba;
}
.inner{
width: 50px;
height: 50px;
background-color: red;
float: left;
}
.clear{
clear: both;
}
4、采用:after
偽元素法(基本上是一種最好的方法了)
<div class="outer clearfix">
<div class="inner"></div>
<div class="inner"></div>
</div>
css
.outer{
width: 200px;
background-color: #04b4ba;
}
.inner{
width: 50px;
height: 50px;
background-color: red;
float: left;
}
.clearfix:after{
content: '';
display: block;
clear: both;
height: 0;
visibility: hidden;
}
.clearfix{
zoom: 1; /*兼容 IE*/
}