高度塌陷:父元素高度自适应,子元素float,造成父元素高度为0;
- 最简单的办法 overflow: hidden;
.box{
width: 500px;
border: 1px solid black;
overflow: hidden;
}
p{
width:100px ;
height: 20px;
background: pink;
float: left;
}
p:nth-child(2){
width: 100px;
height: 30px;
background:red ;
float: left;
}
<div class="box">
<p>h1</p>
<p>p22</p>
</div>
2.在最后一个子元素的后面加一个空div,属性设置clear: both;
.box{
width: 500px;
border: 1px solid black;
}
p{
width:100px ;
height: 20px;
background: pink;
float: left;
}
p:nth-child(2){
width: 100px;
height: 30px;
background:red ;
float: left;
}
.clearboth{
clear: both;
}
<div class="box">
<p>h1</p>
<p>p22</p>
<div class="clearboth"></div>
</div>
3. 伪类选择器的使用,父级div 定义:after
.box{
width: 500px;
border: 1px solid black;
}
p{
width:100px ;
height: 20px;
background: pink;
float: left;
}
p:nth-child(2){
width: 100px;
height: 30px;
background:red ;
float: left;
}
.box:after{
display: block;
clear: both;
content: '';
/*下面这两句话写不写都行*/
visibility: hidden;
height: 0;
}
<div class="box">
<p>h1</p>
<p>p22</p>
</div>