css清除浮动的几种简单方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Rainbow1995/article/details/79255096

在页面的布局和排版中,难免会遇到需要添加浮动和清除浮动的情况,如果不清楚浮动很有可能会造成页面布局塌陷,那么如何清除浮动呢,下边我就来介绍几个简单的方法,亲测有效。

方法一:给父级添加固定的高。例如:

 <style>

 .father{height:500px;} // 给父级添加高度,即可清除浮动对此范围外的影响

.sonLeft{float:left; width:'xx';height:'xx'}

.sonRight{float:right; width:'xx';height:'xx'}

</style>

 <div class=''father>

  <div class='sonLeft'></div>

 <div class='sonRight'></div>

</div>

 用法:适合高度固定的布局,给出明确的高度。

方法二:在浮动结束后加上div标签,添加样式:clear:both,例如:

 <style>

.sonLeft{float:left; width:'xx';height:'xx'}

.sonRight{float:right; width:'xx';height:'xx'}

.bottom{clear:both}

</style>

 <div>

  <div class='sonLeft'></div>

 <div class='sonRight'></div>

</div>

<div class='bottom'></div>

 用法:此方法浏览器支持度高,简单,不过,过多使用会形成较多的空div,造成结构不便于理解。

方法三父级div定义宽度和溢出隐藏样式,不能定义高度。例如:

 <style>

 .father{width:'xx';overflow:hidden} // 给父级添加宽度,溢出部分隐藏,对其他排版不会造成影响

.sonLeft{float:left; width:'xx';height:'xx'}

.sonRight{float:right; width:'xx';height:'xx'}

</style>

 <div class=''father>

  <div class='sonLeft'></div>

 <div class='sonRight'></div>

</div>

用法:不要给具有定位的div添加此样式,会使超出部分隐藏。

方法四:父级定义:overflow:auto。例如:

 <style>

 .father{width:'xx';overflow:auto} // 给父级添加宽度,溢出部分自适应,超出部分滚动

.sonLeft{float:left; width:'xx';height:'xx'}

.sonRight{float:right; width:'xx';height:'xx'}

</style>

 <div class=''father>

  <div class='sonLeft'></div>

 <div class='sonRight'></div>

</div>

用法:当内部div高度超过父级,会出现滚动条,需要特别注意。

猜你喜欢

转载自blog.csdn.net/Rainbow1995/article/details/79255096