css中清除浮動有【clear:both】、after偽元素、對父級設定高度、對父級設定【overflow:hidden】四種方式。其中建議使用的方式是使用after偽元素清除浮動。

本文操作環境:windows10系統、css 3、thinkpad t480電腦。
CSS中清除浮動的四種方式如下:
1、clear:both清除浮動
HTML程式碼:
<div class="container">
<div class="left">left浮动</div>
<div class="right">right浮动</div>
<div class="clear"></div>
</div>CSS程式碼:
<style>
.container{
margin:40px auto;
width:400px;
border:5px solid grey;
background: yellow;/*背景正常显示*/
}
.left{float:left;width:200px;height:100px;border: 1px solid red;}
.right{float:right;width:196px;height:100px;border: 1px solid red;background: blue;} /*边框能撑开*/
.clear{clear:both;}
</style>結果:

父級背景以及邊框也能正常顯示和撐開了,優點方便使用,缺點是會多加HTML空標籤
2、使用after偽元素清除浮動(建議使用)
優點:無需額外的標籤,瀏覽器相容性好,是目前用的最多的一種清除浮動的方法之一,企業都在用;
缺點:ie6-7不支援偽元素:after,使用zoom:1觸發hasLayout.
HTML程式碼:
<div class="container">
<div class="left">left浮动</div>
<div class="right">right浮动</div>
</div>(學習影片分享: css影片教學)
CSS程式碼:
<style>
.container{
width:400px;
border:5px solid grey;
background: yellow;
}
.left{float:left;width:200px;height:100px;border: 1px solid red;}
.right{float:right;width:196px;height:100px;border: 1px solid red;background: blue;}
.container:after{
content:"";
display: block;
clear:both;
}
.container{ *zoom: 1; /*ie6清除浮动的方式 *号只有IE6-IE7执行,其他浏览器不执行*/ }
</style>結果顯示:

3、對父級設定適合CSS高度
一般設定高度需要能確定內容高度才能設定。這裡我們知道內容高度是100PX 上下邊框為2px,這樣具體父級高度為102px,
只需在上面的浮動缺點副作用代碼中的設定類別樣式.container加上父級高度即可,這裡我就不做太多演示了。缺點也非常明顯,本人不建議這樣清除浮動。
4、為父級設定overflow:hidden
原則:父元素定義overflow:hidden,此時,瀏覽器會自動檢查浮動區域的高度;
優點:簡單,無需增加新的標籤;
缺點:不能和position配合使用,因為超出的尺寸的會被隱藏;
代碼也是在副作用基礎上container中添加上overflow: hidden或auto即可實現清除浮動效果
結果顯示:

優缺點:很完美,但屬性太多;不好分別。
相關推薦:CSS教學
以上是css中清除浮動有哪幾種方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!