图片等比例缩放在前端布局中是很常见的,通常拿到的原型设计稿尺寸要求某一个图片位置的容器的高宽我们又不能顺便调整,后端传过来的图片又不是一个固定尺寸,各种横拍竖拍的图片都有;往往这个时候PM就要求‘你让所有大小的图片都在这快区域显示呗’……
不拐弯抹角了,相信大家遇到这事都是先扔width:100%;height:100%。结果是:
图片变形了…
总结了以下几种方案:
- 父元素overflow:hidden,图片设置宽度100%
1
2
3
4
5
6
7
8div {
width: 7.5rem;
height: 5.625rem;
overflow: hidden;
}
img{
widht:100%;
}
效果:
- 高宽auto,设置max-width,max-height
1
2
3
4width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
效果:
- 设置object-fit:cover
1
2
3width: 7.5rem;
height: 5.625rem;
object-fit: cover;
- 不使用img标签,把图片作为背景,通过padding百分比实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21.bunner{
width:265px;
height:200px;
background-color:#3590ea;
overflow: hidden;
}
.imgCover{
width:100%;
height:0;
padding-bottom: 100%;
overflow:hidden;
background-position: center center;
background-repeat: no-repeat;
-webkit-background-size:cover;
-moz-background-size:cover;
background-size:cover;
}
<div class='bunner'>
<div class='imgCover' style='background-image:url(http://pic1.58cdn.com.cn/mobile/big/n_v252a722b32a5a4249adcbef14632ebe73.jpg)'>
</div>
关键点:width:100%;height:0;padding-bottom: 100%;overflow:hidden;padding百分比是根据父元素高宽进行计算的。
相关资料