如何实现全屏图片的background-size:cover效果并叠加小图片?
问题:实现带可定位小元素的全屏cover背景效果
我需要实现一张图片全屏填充的效果,和给body设置background-image并将background-size设为cover的效果一致,同时要在这张图片上放置小图片制作动画(比如动物出现在树上的效果)。因为需要按背景图片的百分比定位和设置小图片尺寸,所以不能直接用background-image。
我尝试把背景图片放进容器,小图片设为容器内的绝对定位元素,再通过min-width和min-height模拟cover效果,但效果不完全一致:在Firefox中,图片的缩小比例跟不上屏幕的缩小比例。
真实cover效果示例
(点击“全屏”,使用“开发者工具”>“响应式设计模式”调整屏幕大小)
body { height: 100vh; margin: 0px; background-image: url(https://images.unsplash.com/photo-1683009427619-a1a11b799e05?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D); background-size: cover; background-repeat: no-repeat; background-position: center; }
模拟cover效果示例
body { height: 100vh; margin: 0px; display: flex; overflow: hidden; place-content: center; place-items: center; } #img_wrapper { position: relative; width: fit-content; height: fit-content; } #bg_img { min-width: 100vw; min-height: 100vh; } #cat { position: absolute; left: 40%; top: 50%; width: 10%; }
<div id="img_wrapper"> <img id="bg_img" src="https://images.unsplash.com/photo-1683009427619-a1a11b799e05?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"> <img id="cat" src="https://cdn.pixabay.com/photo/2017/09/01/00/15/png-2702691_960_720.png"> </div>
可以看到(至少在Firefox中),小图片的位置和尺寸保持正确,图片也能覆盖屏幕,但无法像background-size:cover那样取最小覆盖尺寸,比如移动端屏幕下,图片底部中间的人物会很快消失,而真实cover效果不会。
请问如何修复该问题?或有没有更好的方法实现需求(在任意屏幕尺寸下,在大图上放置小图片)?
编辑补充
CBroe的解决方案有效,以下是完整示例:
我将其居中方案替换为flexbox,但不影响结果。核心思路是使用固定比例的容器(正方形),给容器设置background-image,使其相对容器边框不会“移位”,再通过vmax单位让容器始终覆盖屏幕。
最终效果示例:
body { height:100vh; overflow: hidden; /* flex centering method : */ display: flex; place-content: center; place-items: center; } #img_wrapper { position: relative; background-image: url("https://images.unsplash.com/photo-1683009427619-a1a11b799e05?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"); background-repeat: no-repeat; background-size: cover; background-position: center; /* to get the square around the screen : */ /* (change to vmin to get it inside the screen) */ width: 100vmax; height: 100vmax; /* to avoid flex centering to shrink the width : */ flex-shrink: 0; } #cat { position: absolute; left: 40%; top: 50%; width: 10%; }
<div id="img_wrapper"> <img id="cat" src="https://cdn.pixabay.com/photo-1683009427619-a1a11b799e05?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"> </div>
内容的提问来源于stack exchange,提问作者hugogogo
相关产品推荐
相关产品推荐

