一.浮动的副作用
当元素设置float浮动后,该元素就会脱离文档流并向左/向右浮动.
1 浮动元素会造成父元素高度塌陷
2 后续元素会受到影响
二.清除浮动
当父元素出现塌陷的时候,对布局是不利的,所以我们必须清除副 作用 解决方案有很多种
1 父元素设置高度
如果父元素高度塌陷,可以给父元素设置高度,撑开元素本身大小
2 受影响的元素增加clear属性
3 overflow清除浮动
如果有父级塌陷,并且同级元素也收到了影响,可以使用 overflow 清 除浮动 这种情况下,父布局不能设置高度 父级标签的样式里面加: overflow:hidden;clear: both;
4 伪对象方式
如果有父级塌陷,并且同级元素也收到了影响,还可以使用伪对象 方式处理 为父标签添加伪类 after ,设置空的内容,并且使用display: block; clear:both ; 这种情况下,父布局不能设置高度
三.实例
受影响的元素增加clear属性
处理前
在受影响的元素增加clear属性后
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .container { width: 400px; background-color: aquamarine; } .box { width: 100px; height: 100px; background-color: beige; float: left; margin: 6px; } .text { width: 100px; height: 100px; background-color: rebeccapurple; margin: 6px; clear:both; } </style> </head> <body> <div class="container"> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="text"></div> </div> </body> </html>
overflow清除浮动
处理前:
处理后:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .container { width: 400px; background-color: aquamarine; overflow: hidden; clear: both; } .box { width: 100px; height: 100px; background-color: beige; float: left; margin: 6px; } .text { width: 100px; height: 100px; background-color: rebeccapurple; margin: 6px; /* 后续元素选择这个选择器,不管在<div class="container">里面,还是外面, 都能防止父元素出现高度塌陷! */ clear: both; } </style> </head> <body> <div class="container"> <div class="box"></div> <div class="box"></div> <div class="box"></div> </div> <div class="text"></div> </body> </html>
伪对象方式
处理前
处理后:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .container { width: 400px; background-color: aquamarine; } .container::after { content: ""; display: block; clear: both; } .box { width: 100px; height: 100px; background-color: beige; float: left; margin: 6px; } .text { width: 100px; height: 100px; background-color: rebeccapurple; margin: 6px; } </style> </head> <body> <div class="container"> <div class="box"></div> <div class="box"></div> <div class="box"></div> </div> <div class="text"></div> </body> </html>