如何像操作div一样堆叠移动图片并保持父容器约束及宽高比
修改方案
第一步:调整body基础样式
消除默认边距,让内容始终居中显示在视口内:
body { margin: 0; min-height: 100vh; display: flex; justify-content: center; align-items: center; }
第二步:调整.box-1容器样式
修改.box-1的CSS规则如下:
.box-1 { /* 限制容器最大尺寸不超出视口 */ max-width: 100vw; max-height: 100vh; /* 填写你最底层背景图的实际宽高比,比如16:9就填16/9,4:3就填4/3 */ aspect-ratio: 16/9; display: grid; grid-template-columns: repeat(7, 1fr); grid-template-rows: repeat(7, 1fr); }
第三步(可选):调整图片填充规则
如果希望图片完整显示不被裁剪,可以把img样式中的object-fit: cover改为object-fit: contain:
img { width: 100%; height: 100%; /* contain保证图片完整显示,cover会裁剪多余部分铺满容器 */ object-fit: contain; border: solid; }
原理说明
aspect-ratio会让容器始终保持和背景图一致的宽高比,不会出现拉伸变形max-width和max-height限制容器最大不会超出视口边界,不管视口是过宽还是过高,容器都会自动等比缩放适配- body的flex布局让整个容器始终居中显示,避免默认边距导致的滚动条问题
可选兼容方案(适配不支持aspect-ratio的老旧浏览器)
如果需要兼容旧版浏览器,可以改用定位方案实现:
.box-1 { position: relative; max-width: 100vw; max-height: 100vh; } /* 最底层背景图放在正常文档流里撑开父容器 */ img:nth-child(1) { display: block; width: auto; height: auto; max-width: 100vw; max-height: 100vh; } /* 其他子图片全部绝对定位,用百分比调整位置 */ img:not(:nth-child(1)) { position: absolute; width: 30%; left: 0; bottom: 0; } .rocket { width: 10%; left: 30%; bottom: 10%; transform: rotate(45deg); }
内容的提问来源于stack exchange,提问作者Hackem2bits
相关产品推荐
相关产品推荐

