如代码所示,div1,div2,div3都是左浮动的。父元素box撑不开。
<div class="box">
<div class="div div1"></div>
<div class="div div2"></div>
<div class="div div3"></div>
<!--<p style="clear: both"></p>-->
</div>
解决方法:
1.直接设置父元素height
.box{
border: 1px solid #00d6b2;
/*height: 102px;*/
}
2.父元素设置overflow:hidden
.box{
border: 1px solid #00d6b2;
/*overflow: hidden;*/
}
3.父元素内末尾添加一个元素
意思就是在父元素内末尾添加一个元素 清楚浮动clear:both;
<div class="box">
<div class="div div1"></div>
<div class="div div2"></div>
<div class="div div3"></div>
<!--<p style="clear: both"></p>-->
</div>
4.伪类方法 父元素:after
意思就是在父元素后面加一个空格,设置这个空格clear:both;display:block;visibility:hidden;height:0;
.box:after{
content: " ";
clear: both;
display: block;
visibility: hidden;
height: 0;
}
最后,完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title</title>
<script type="text/javascript">
</script>
<style type="text/css">
.box{
border: 1px solid #00d6b2;
/*height: 102px;*/
/*overflow: hidden;*/
}
.box:after{
content: " ";
clear: both;
display: block;
visibility: hidden;
height: 0;
}
.div{
border: 1px solid black;
float: left;
width: 100px;
height: 100px;
}
.div1{
background-color: red;
}
.div2{
background-color: greenyellow;
}
.div3{
background-color: pink;
}
</style>
</head>
<body>
<div class="box">
<div class="div div1"></div>
<div class="div div2"></div>
<div class="div div3"></div>
<!--<p style="clear: both"></p>-->
</div>
</body>
</html>