
无限制拖拽容器中的图片自适应
问题:
如何使容器中的图片在容器大小无规则拖拽、任意宽高的情况下,始终保持在容器内且不失真?
最终效果:
[图像]
例子:
[demo]
解决方案:
img {
// width: 100%;
// height: auto;
max-width: calc(100% - 40px);
max-height: calc(100% - 40px);
position: absolute;
inset: 20px;
margin: auto;
}说明:
- 去掉原有的 width: 100%; 和 height: auto;。
- 设置 max-width 和 max-height,保证图片尺寸不超过容器尺寸。
- 设置 position: absolute;,使图片相对于容器定位。
- 设置 inset: 20px;,在容器内留出 20px 的边距。
- 设置 margin: auto;,使图片在容器内水平垂直居中。
通过这种方式,图片可以适应任意宽高的容器,并始终保持在一个合理的大小和位置内。










