当前位置 博文首页 > m0_53521757的博客:CSS中解决父布局塌陷问题
???????因为子元素浮动后,会脱离文档流。导致子元素无法撑起父元素的高度,造成父元素高度塌陷(父元素占据子元素原来的位置,此时父元素也没有设置高度,没有内容撑开父级高度)
起始状态
<style type="text/css">
#div_01{
background-color: antiquewhite;
}
#div_02{
height: 100px;
width: 100px;
background-color: red;
}
#div_03{
height: 100px;
width: 100px;
background-color: aqua;
}
</style>
<div id="div_01">
<div id="div_02"></div>
<div id="div_03"></div>
</div>
子元素浮动后,造成父布局塌陷:
<style type="text/css">
#div_01{
background-color: antiquewhite;
}
#div_02{
height: 100px;
width: 100px;
background-color: red;
}
#div_03{
float: left;
height: 100px;
width: 100px;
background-color: aqua;
}
</style>
解决方法:
1.给父级元素一个高度
<style type="text/css">
#div_01{
height: 200px;
background-color: antiquewhite;
}
#div_02{
height: 100px;
width: 100px;
background-color: red;
}
#div_03{
float: left;
height: 100px;
width: 100px;
background-color: aqua;
}
</style>
2.给父元素添加overflow属性方法,触发BFC(overflow:hidden/auto)
<style type="text/css">
#div_01{
overflow: auto;
background-color: antiquewhite;
}
#div_02{
height: 100px;
width: 100px;
background-color: red;
}
#div_03{
float: left;
height: 100px;
width: 100px;
background-color: aqua;
}
</style>
3.clear属性:在最后一个子元素后加一个空的div,给他添加样式clear,清除两侧浮动
<style type="text/css">
#div_01{
background-color: antiquewhite;
}
#div_02{
height: 100px;
width: 100px;
background-color: red;
}
#div_03{
float: left;
height: 100px;
width: 100px;
background-color: aqua;
}
#div_empty{
clear: left;
}
</style>
<div id="div_01">
<div id="div_02"></div>
<div id="div_03"></div>
<div id="div_empty"></div>
</div>
4.给父级元素一个padding
<style type="text/css">
#div_01{
background-color: antiquewhite;
padding:100px;
}
#div_02{
height: 100px;
width: 100px;
background-color: red;
}
#div_03{
float: left;
height: 100px;
width: 100px;
background-color: aqua;
}
</style>
5.使用after伪元素清除浮动
<style type="text/css">
#div_01{
background-color: antiquewhite;
/* display: inline-block; */
}
#div_02{
height: 100px;
width: 100px;
background-color: red;
}
#div_03{
float: left;
height: 100px;
width: 100px;
background-color: aqua;
}
.cls::after{
content: "";
clear: both;
display: block;
}
</style>
<div id="div_01" class="cls">
<div id="div_02"></div>
<div id="div_03"></div>
</div>
6.使用before和after双伪元素清除浮动(终极解决方案,强烈推荐,以后直接拿来用)
<style type="text/css">
#div_01{
background-color: antiquewhite;
/* display: inline-block; */
}
#div_02{
height: 100px;
width: 100px;
background-color: red;
}
#div_03{
float: left;
height: 100px;
width: 100px;
background-color: aqua;
}
.cls::after,.cls::before{
content: "";
clear: both;
display: block;
}
</style>
<div id="div_01" class="cls">
<div id="div_02"></div>
<div id="div_03"></div>
</div>
cs