浮动的清除方式

在什么时候需要用到浮动呢?

我们都知道当需要一个左中右三列布局的时候,就需要给左中右的三个div添加float

添加了浮动有什么影响呢?

 当一个内层元素是浮动的时候,其父元素也就不再包含这个浮动的内层元素,因为此时浮动的元素已经脱离的文档流。这个时候外层的div就无法被撑开,margin也会失效。

这时候我们就需要清除浮动。。。看下面的demo

<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;}
</style>
<div class="outer">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div> 
</div>

 这时候我们没有清除浮动,外层的div没有被撑开 ,效果图为:

第一种方法:给内层元素加一个空的div然后加样式清除

<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;} </style> <div class="outer"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div>
<div class="clear"></div> </div>

 第二种方法:给外层元素加overflow

<style>
.outer{border: 1px solid #ccc;background: #fc9;color: #fff; margin: 50px auto;padding: 50px; overflow:hidden;}
.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;}
</style>
<div class="outer">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>  
</div>

 第三种方法:利用伪元素after,类似给内层元素添加一个div

<style>
.outer{border: 1px solid #ccc;background: #fc9;color: #fff; margin: 50px auto;padding: 50px;}
.outer:after{content: ''; display: block; clear: both; height: 0; visibility: hidden;}
.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;} </style> <div class="outer"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> </div>

原文地址:https://www.cnblogs.com/hfxm/p/5588306.html