容器包含若干个元素如何清除浮动

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;来实现


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