正常页面布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | *{ margin:0; padding: 0; } .content{ width:400px; border:1px solid #000; } .box{ width:200px; height:200px; background: greenyellow; } < div class = "content" > < div class = "box" ></ div > </ div > < p >基苦阿斯蒂芬</ p > |
当给类名为.box的盒子加上浮动后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | *{ margin : 0 ; padding : 0 ; } .content{ width : 400px ; border : 1px solid #000 ; } .box{ width : 200px ; height : 200px ; background : greenyellow; float : left ; } |
可以看到页面布局已经乱了,因为元素设置浮动后会脱离文档流
解决方案
1 利用BFC(给父元素加上overflow:hidden)
**缺点:父元素溢出的元素会隐藏,可能会影响页面显示 **
1 2 3 4 5 6 | .content{ width : 400px ; border : 1px solid #000 ; overflow : hidden ; } |
2 加空div
要点:
1.加上一个空的块级元素
2.对块级元素进行清除浮动, 省事方法,不管理是左浮还是右浮,直接全清(clear:both)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | *{ margin:0; padding: 0; } .content{ width:400px; border:1px solid #000; /* overflow: hidden; */ } .box{ width:200px; height:200px; background: greenyellow; float: left; } .clear{ clear: both; } < div class = "content" > < div class = "box" ></ div > < div class = "clear" ></ div > </ div > < p >基苦阿斯蒂芬</ p > |
3 利用伪元素
要点:
1 其实和加空div的原理是一致的,唯一要记住的就是把伪元素转为块级元素(display:block),否则会没有效果
2 还有伪元素的属性不要忘记加上(content:‘’)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | *{ margin : 0 ; padding : 0 ; } .content{ width : 400px ; border : 1px solid #000 ; /* overflow: hidden; */ } . content ::after{ content : '' ; display : block ; // 必须要转换为块元素 clear : both ; } .box{ width : 200px ; height : 200px ; background : greenyellow; float : left ; } /* .clear{ clear: both; } */ <div class= "content" > <div class= "box" ></div> </div> <p>基苦阿斯蒂芬</p> |
到此这篇关于CSS浮动引起的高度塌陷问题的文章就介绍到这了,更多相关CSS浮动高度塌陷内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章,希望大家以后多多支持IT俱乐部!