容器包含若干個元素如何清除浮動

1.添加新的元素

<style>
.outer{border:1px solid #ccc;background: #fc9;color: #fff;margin: 50px auto;padding:50px;}
.div1{width:80px;height:80px;background: red;float: left;}
.div2{width:80px;height:80px;background: blue;float: left;}
.div3{width:80px;height:80px;background: sienna;float: left;}
.clear{clear:both;height: 0; line-height: 0; font-size: 0};
</style>

<!--方法一 添加新的元素 、應用 clear:both; -->
<div class="outer">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<!-- 1 -->
<div class="clear"></div>
</div>

缺點:每次清除浮動的時候都需要增加一個空標籤來使用。-ha頁面複雜的佈局要經常清楚浮動的時候就會產生很多的空標籤,增加了頁面無用標籤,不利於頁面優化

2.給父級元素定義

<style>
.outer{border:1px solid #ccc;background: #fc9;color: #fff;margin: 50px auto;padding:50px;}
.div1{width:80px;height:80px;background: red;float: left;}
.div2{width:80px;height:80px;background: blue;float: left;}
.div3{width:80px;height:80px;background: sienna;float: left;}
.clearfix{zoom:1;overflow: hidden;};
</style>

<!-- 方法二 給父級元素定義 -->
<div class="outer clearfix">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</div>

3.使用僞元素

<style>
.outer{border:1px solid #ccc;background: #fc9;color: #fff;margin: 50px auto;padding:50px;}
.div1{width:80px;height:80px;background: red;float: left;}
.div2{width:80px;height:80px;background: blue;float: left;}
.div3{width:80px;height:80px;background: sienna;float: left;}
.clearfix{*zoom:1};
.clearfix::before{
content: '';
display: table;
}
.clearfix::after{
content: '';
display: table;
clear: both;
}
</style>
<div class="outer clearfix">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</div>
不用display:inline-block和block是因爲⑦會產生多餘空白,而使用display:table可以創建一個隱藏的空白元素從而達到清除浮動的效果。而且代碼簡單。當然也可以使用原生的,display爲block然後設置content:“”,width:0;height:0;visibility:hiddden;來實現


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章