如果子元素根据父元素设置宽度,那么将其高度设置为0,并将padding-bottom设置为百分比,则该子元素的高度将根据它的宽度计算。
<div class="div1">
<div class="div2"></div>
</div>
.div1{
width:400px;
height:800px;
}
.div2{
width:100%;
height:0;
padding-bottom:100%;
background-color: #0f8bcb;
}
上述方法不适用于图片。如果子元素是图片,需要使用下面的方法。
<div class="div1">
<div class="right-img-block">
<img src="./sheep.png" class="right-img"/>
</div>
</div>
.div1{
width:400px;
height:800px;
}
.img-block{
width:100%;
height:0;
padding-bottom:100%;
position: relative;
}
.img{
width:100%;
height:100%;
position: absolute;
top:0;
left:0;
}