CSS img正方形图片
需求:后端返回了一组图片,图片的宽度固定,高度不固定。前端要求图片展示为正方形,图片不能变形且自适应,如果图片高了则裁剪掉。
<div>
<div class="img-wrap">
<img src="a.jpg">
</div>
</div>
// css
.img-wrap {
position: relative;
width: 100%;
height: 0;
padding-bottom: 100%;
overflow: hidden;
}
.img-wrap img {
position: absolute;
width: 100%;
}
原理解析:img-wrap继承父元素的宽度,为了保证img-wrap容器的高度等于宽度,通过padding-bottom撑开高度,接下来图片只设置宽度让它等于父元素的宽度,图片的高度会自适应。父元素设置overflow:hidden,这样设置以后图片即使过高也能保证不变形,只是看起来像裁剪成了正方形。
胖胖熊笔记,笔记已迁移

浙公网安备 33010602011771号