CSS:如何在background-position变换后保持section充满背景图
解决背景图位移后露出空白的问题
你的问题核心是background-attachment: fixed结合background-position位移时,背景图是相对于视口固定的,位移后原元素区域会露出视口外的空白;另外父元素未设置定位导致absolute元素的参考对象错误,还有默认边距的影响。以下是修复方案:
修改后的完整代码
HTML
<section> <div class="firstpage"></div> </section>
CSS
/* 清除默认边距,避免间隙 */ body, section { margin: 0; padding: 0; } /* 让section占满视口高度,并设置相对定位作为子元素absolute的参考 */ section { position: relative; min-height: 100vh; } .firstpage { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-image: url('https://i.ibb.co/HGSY9Rv/bcb.png'); /* 移除fixed,让背景图相对于当前元素固定 */ background-attachment: scroll; background-position: center; background-repeat: no-repeat; background-size: cover; }
JavaScript
$(".firstpage").mouseenter(function(){ $(this).animate({ 'background-position-x': '-200px', }); }); $(".firstpage").mouseleave(function(){ $(this).animate({ 'background-position-x': '0px', }); });
关键修改点说明
- 移除background-attachment: fixed:fixed会让背景图绑定到视口,位移时元素区域会露出视口外的空白。改用默认的scroll后,背景图绑定到.firstpage元素,位移时只会在元素内部移动,不会露出空白。
- 给section设置position: relative和min-height: 100vh:确保.firstpage的absolute定位以section为参考,同时section占满视口高度,避免出现高度不足的问题。
- 清除body和section的默认边距:消除浏览器默认样式带来的间隙,避免露出body背景。
- 给.firstpage添加top:0和left:0:确保absolute元素完全覆盖section的左上角,避免出现偏移。
内容的提问来源于stack exchange,提问作者Game Boyz
相关产品推荐
相关产品推荐

