Skip to content

用css实现图片等比缩放裁剪

问题描述

想要将后台传来的图片放在一个固定容器里,但是接口返回的图片大小不一致。所以希望先对图片做一个等比缩放,然后按照容器尺寸裁剪,显示图片的中间部分

解决方案

css
.photo-box {
  width: 80px;
  height: 80px;
  background-image: url(/assets/img/demo.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}

核心:background-size: cover;自动判断短边,将图片以短边为基准去缩放。background-position: center center;将图片定位到中间

参考链接

css中如何做到容器按比例缩放

Designed & Powerd by liujun