屏幕缩放时CSS背景图位置偏移问题求助(附代码)
嘿,这个背景图偏移的问题我太熟了!让我帮你拆解一下原因,再给你搞定它~
问题到底出在哪?
你在内部容器的background属性里加了fixed这个关键词,它对应的是background-attachment: fixed——这个属性会让背景图死死钉在浏览器的视口上,而不是跟着它所在的容器走。当你调整屏幕尺寸时,容器的位置会跟着页面布局变化,但背景图还停在视口的固定位置,这不就偏移了嘛!
另外,你写的动画里重复把整个background属性写了一遍,这会不小心覆盖掉之前设置的background-size: cover,也是个隐藏的小坑。
直接上修复方案
我帮你改了两处核心地方,保证背景图在任何屏幕尺寸下都乖乖紧贴外部容器的背景下方:
修改后的 CSS 代码
/* 外部容器:保持原来的背景和高度设置就行 */ .container-titolo-index-big-background { background: url("../img/home/1.jpg") no-repeat center center; height: 400px; max-width: 100% !important; width: 100% !important; } /* 内部容器:把讨厌的fixed去掉,统一设置背景基础属性 */ .container-titolo-index { max-width: 100% !important; width: 100% !important; background: url("../img/home/2.jpg") no-repeat center center; background-size: cover; animation: slideshowHome 16s infinite; height: 430px; } /* 动画优化:只改背景图,其他属性复用上面的,避免重复代码 */ @keyframes slideshowHome { 0% { background-image: url("../img/home/2.jpg"); } 16% { background-image: url("../img/home/3.jpg"); } 32% { background-image: url("../img/home/4.jpg"); } 48% { background-image: url("../img/home/5.jpg"); } 64% { background-image: url("../img/home/6.jpg"); } 80% { background-image: url("../img/home/1.jpg"); } 100% { background-image: url("../img/home/2.jpg"); } }
HTML 代码保持不变
<div class="container-titolo-index-big-background"> <div class="container-titolo-index"></div> </div>
额外小建议
如果你本来就想让两个容器上下分开(而不是嵌套),可以把HTML改成并列结构,这样背景图衔接会更自然,也不会有容器溢出的隐患:
<div class="container-titolo-index-big-background"></div> <div class="container-titolo-index"></div>
内容的提问来源于stack exchange,提问作者Orange Orange
相关产品推荐
相关产品推荐

