解决父级塌陷问题(父元素坍塌问题)五种解决方法
当子元素脱离文档流时,会导致父级元素的高度坍塌,从而导致该元素下面的元素位置错乱,从而影响整体页面的布局。
因此,在这里整理了一下解决该问题的方法:
<body>
<!-- html 布局,下面仅放css代码-->
<div class="box">
<div class="a1"></div>
<div class="a2"></div>
<div class="a3"></div>
</div>
</body>
1.当已知父元素的高度,只需要给父级元素设置相应的高度即可
解决效果图都一样,再此只放一张图
<style>
/* 样式 */
.box {
width: 100%;
background-color: plum;
/*给父元素添加高度*/
height: 150px;
}
.a1,.a2,.a3{
float: left;
}
.a1 {
width: 100px;
height: 100px;
background-color: paleturquoise;
}
.a2{
width: 150px;
height: 150px;
background-color: pink;
}
.a3{
width: 50px;
height: 50px;
background-color: palegreen;
}
</style>
2.给父元素添加 overflow:hidden;(缺点:溢出部分的内容会被隐藏)
/* 样式 */
.box {
width: 100%;
background-color: plum;
/* 给父元素添加overflow: hidden; */
overflow: hidden;
}
.a1,.a2,.a3{
float: left;
}
.a1 {
width: 100px;
height: 100px;
background-color: paleturquoise;
}
.a2{
width: 150px;
height: 150px;
background-color: pink;
}
.a3{
width: 50px;
height: 50px;
background-color: palegreen;
}
3.给受影响的元素添加 clear:both; (让受影响的元素回到正常位置,但是塌陷的父元素高度并未找回)
<style>
/* 样式 */
.box {
width: 100%;
background-color: plum;
}
.a1,.a2,.a3{
float: left;
}
.a1 {
width: 100px;
height: 100px;
background-color: paleturquoise;
}
.a2{
width: 150px;
height: 150px;
background-color: pink;
}
.a3{
width: 50px;
height: 50px;
background-color: palegreen;
}
/*给受影响的元素清楚影响*/
.box2{
width: 200px;
height: 100px;
background-color: gold;
clear: both;
}
</style>
<body>
<!-- html -->
<div class="box">
<div class="a1"></div>
<div class="a2"></div>
<div class="a3"></div>
</div>
/*这个box2是被影响的元素,若不解决塌陷问题,该元素会被遮挡*/
<div class="box2"></div>
</body>
4.添加空div(给塌陷高度的父元素内容最后面添加一个空的div,div设置clear:both;)(会使页面多出很多无语义的空div)
<style>
/* 样式 */
.box {
width: 100%;
background-color: plum;
}
.a1,.a2,.a3{
float: left;
}
.a1 {
width: 100px;
height: 100px;
background-color: paleturquoise;
}
.a2{
width: 150px;
height: 150px;
background-color: pink;
}
.a3{
width: 50px;
height: 50px;
background-color: palegreen;
}
/*给空div添加clear:both;*/
.a4{
clear: both;
}
</style>
<body>
<!-- html -->
<div class="box">
<div class="a1"></div>
<div class="a2"></div>
<div class="a3"></div>
/*添加空div*/
<div class="a4"></div>
</div>
</body>
5.5)给父元素添加伪类 (由方法4引申出的方法,目前最好用)
<style>
/* 样式 */
.box {
width: 100%;
background-color: plum;
}
.a1,.a2,.a3{
float: left;
}
.a1 {
width: 100px;
height: 100px;
background-color: paleturquoise;
}
.a2{
width: 150px;
height: 150px;
background-color: pink;
}
.a3{
width: 50px;
height: 50px;
background-color: palegreen;
}
/* 给父元素添加伪类 */
.box::after{
content: '';
display: table;
clear: both;
}
欢迎大家在评论区交流方法,探讨学习思路.