css清除浮动的方法总结


浮动后元素可以很好的帮我们进行页面上的布局,但是浮动后我们为什么要清除浮动呢?其实,清除浮动的本质是因为,子元素浮动,引起父元素内部高度为零,而后边元素因为前边元素高度为零,从而影响布局,最简单直接方法是为父元素添加高度,但是在我们真正实际开发中,是不方便也给父元素添加固定高度,比如,新闻页面,怎么知道有多少个字呢?高度怎么计算呢?
以下面的代码为例子:

<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>

9328491c2d0ecb97a1a560ea4bb7be9.png
两个子盒子浮动,脱离标准流,不占有位置,父元素没有高度,后边box2盒子就会跑上来

  1. 额为标签法

在浮动子元素后边,添加一个空盒子,代码如下:

  <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>

06a74780d823d9fb74f06e674c30501.png

2.给父元素添加overflow:hidden,这个是触发到BFC
aa7f936be4bc96876cc19cac263b7cc.png
也可以达到我们想要的效果
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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM