React中如何固定div背景图片,实现内容滚动背景静止
背景图固定不随内容滚动的解决办法
你的问题出在当前容器的滚动逻辑和background-attachment:fixed的生效条件上,试试下面几个方案:
方案一:调整容器的滚动行为
你给.desktopView设了height:100vh,但内部内容超出后,滚动条可能跑到body上了,导致背景固定的效果不对。修改CSS:
/* 修改desktopView样式 */ .desktopView { height: 100vh; width: 100vw; background-image: url('./assets/bg.png'); background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover; overflow-y: auto; /* 让容器自己产生滚动条 */ } /* 禁用body的滚动 */ body { margin: 0; overflow: hidden; }
方案二:用伪元素做独立背景层
如果background-attachment:fixed还是不生效,换个思路用伪元素创建固定背景,兼容性更好:
.desktopView { height: 100vh; width: 100vw; position: relative; overflow-y: auto; /* 容器自身滚动 */ } /* 伪元素做固定背景 */ .desktopView::before { content: ""; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: url('./assets/bg.png'); background-position: center; background-repeat: no-repeat; background-size: cover; z-index: -1; /* 把背景压在内容下面 */ }
额外检查
看看Header、Navbar、Content这些子组件有没有设置position:fixed或者transform属性,这些会干扰背景固定的效果,需要调整。
内容的提问来源于stack exchange,提问作者Varun Pandey
相关产品推荐
相关产品推荐

