一、介绍
当父元素设置高度为100%时,那么其伪类(::before和::after),可以设置padding-top或padding-bottom改变父元素高度。
如:父元素设置如下
<style>
.nav{
width: 200px;
height: 100%;
background-color: red;
}
</style>
<div class="father"></div>
那么通过浏览器可以看到盒子模型如下:可见盒子高度为0
当使用伪类(::before或::after)设置padding-top或padding-bottom时,会根据父元素的宽度来设置padding-top或padding-bottom,从而撑开父元素的高度,达到设置父元素高度的效果。
代码如下:
<style>
.nav{
width: 200px;
height: 100%;
background-color: red;
}
.nav::before{
content: "";
/*根据宽度撑开高度*/
padding-top: 150%;
background-color: orange;
/*因为伪类默认是行内元素*/
display: block;
}
</style>
当添加上述代码之后,父元素就会被撑开(这时伪类高度是0)
二、这样做有什么好处?
1.这样做就可以更好的做响应式布局,当父元素的宽度也是不定的(如100%),那么就基本可以实现动态的布局。
2.也可以在此处解决高度塌陷和垂直方向外边距重叠。
三、小案例:在撑开的父元素上设置背景图片
<style>
.nav{
width: 200px;
height: 100%;
background-color: red;
position: relative;
}
.nav::before{
content: "";
padding-top: 150%;
width: 100%;
background-color: orange;
display: block;
}
.inner{
background-image: url(./test.jpeg);
background-size: cover;
background-origin: center;
background-position: center;
/*使背景图片完全铺平父元素*/
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<div class="nav">
<div class="inner"></div>
</div>
得到一个200*300大小的背景图片。