有时候我们需要再页面的拉拽中保持元素的宽高比,那如何实现呢?注:这也是我在面试中遇到的一个问题。
大致可以分两种情况
- 元素有固定的宽度高度
比如
<image>、<video>...那这种就简单了,我们只需要设定好width,高度auto就行了。
HTML
<div class="wrapper">
<img src="http://lc-BfuEKENC.cn-n1.lcfile.com/ad4183648706aa9c1ffc.JPG" alt="">
</div>
CSS
.wrapper{
width:40vw;
}
img{
width:80%;
height:auto;
}
- 普通块级元素
这就可以用到padding-bottom这个属性了,用法:
1.<length>
填充的大小为固定值。必须为非负数。
2.<percentage>
相对于包含块的宽度,以百分比为单位的填充大小。必须为非负数。
HTML
<div class="wrapper">
<div class="test"></div>
</div>
CSS
.wrapper{
width:40vw;
padding:2px;
}
.test{
width:100%;
background:grey;
height:0;
padding-bottom: 75%;
}