介绍的四种方法都在下面源码的基础上修改演示!
<!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>
.div1 {
width: 100%;
/* display: inline-block; */
background-color: pink;
}
.div2 {
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
.div3 {
width: 200px;
height: 200px;
background-color: orange;
float: right;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
<div class="div3"></div>
</div>
</body>
</html>
由于两个子元素都设置了浮动,造成粉色的父元素没有高度
方法如下:
1.给父容器上设置属性: display:inline-block
.div1 {
width: 100%;
display: inline-block;
background-color: pink;
}
2.给父容器上设置属性: overflow:auto
.div1 {
width: 100%;
overflow: auto;
background-color: pink;
}
3.给父容器设置:after伪类(:after伪类会追加在父元素所有内容的最后面):
.div1:after{
/*设置内容为空*/
content:"";
/*设置为块级元素*/
display:block;
/*清除浮动*/
clear:both
}
三个方法解决后都如下图,浮动清除,粉色的父元素又出现了!