浮動后元素可以很好的幫我們進行頁面上的布局,但是浮動后我們為什么要清除浮動呢?其實,清除浮動的本質是因為,子元素浮動,引起父元素內部高度為零,而后邊元素因為前邊元素高度為零,從而影響布局,最簡單直接方法是為父元素添加高度,但是在我們真正實際開發中,是不方便也給父元素添加固定高度,比如,新聞頁面,怎么知道有多少個字呢?高度怎么計算呢?
以下面的代碼為例子:
<style> .son1, .son2 { width: 100px; height: 50px; background-color: skyblue; float: left; } .box1 .son2 { background-color: yellow; } .box2 { width: 500px; height: 200px; background-color: purple; } </style> </head> <body> <div class="box1"> <div class="son1">我是son1</div> <div class="son2">我是son2</div> </div> <div class="box2">我是box2</div> </body>
兩個子盒子浮動,脫離標准流,不占有位置,父元素沒有高度,后邊box2盒子就會跑上來
- 額為標簽法
在浮動子元素后邊,添加一個空盒子,代碼如下:
<style> .son1, .son2 { width: 100px; height: 50px; background-color: skyblue; float: left; } .box1 .son2 { background-color: yellow; } .box2 { width: 500px; height: 200px; background-color: purple; } /* 2、此處設置clear: both */ .clear { clear: both; } </style> </head> <body> <div class="box1"> <div class="son1">我是son1</div> <div class="son2">我是son2</div> <!-- 1、在浮動盒子后邊添加一個空盒子 --> <div class="clear"></div> </div> <div class="box2">我是box2</div> </body>
2.給父元素添加overflow:hidden,這個是觸發到BFC
也可以達到我們想要的效果
3.利用after偽元素清除浮動
.clearfix:after { display: block; visibility: hidden; content: "."; height: 0; clear: both; } .clearfix { *zoom: 1; /*此處是為ie6、7處理的方式 */ } .son1, .son2 { width: 100px; height: 50px; background-color: skyblue; float: left; } .box1 .son2 { background-color: yellow; } .box2 { width: 500px; height: 200px; background-color: purple; } </style> </head> <body> <div class="box1 clearfix"> <div class="son1">我是son1</div> <div class="son2">我是son2</div> </div> <div class="box2">我是box2</div>
4.雙偽元素清除浮動,這個也是我們最推薦的一種方式
<style>
.clearfix:before,.clearfix:after { content: ''; display: table; } .clearfix:after { clear: both } .clearfix { *zoom: 1; } .son1, .son2 { width: 100px; height: 50px; background-color: skyblue; float: left; } .box1 .son2 { background-color: yellow; } .box2 { width: 500px; height: 200px; background-color: purple; } </style> </head>