如何实现占屏幕100%高度且背景图固定的div,滚动显示后续内容?
Full-Screen Fixed Background Div with Scrollable Content Below
Got it, let's get your desired effect working smoothly! Your existing code is almost there—we just need a few small tweaks to ensure the full-screen div behaves correctly and the background stays fixed as you scroll.
Key Adjustments Needed:
- Reset default browser margins/paddings to eliminate unwanted gaps
- Use
100vhinstead of100%for more reliable full-screen height (it directly references the viewport height, avoiding issues with parent element height inheritance) - Ensure no unintended overflow that breaks the layout
Corrected Code:
HTML
<body> <div class="main-bg"></div> <div style="height: 400px; background: red;" class="after"></div> </body>
CSS
/* Reset default browser styles */ body, html { height: 100%; width: 100%; margin: 0; padding: 0; overflow-x: hidden; /* Prevent horizontal scroll */ } .main-bg { background: url(../images/bg-img.jpg); background-repeat: no-repeat; background-position: center center; background-size: cover; background-attachment: fixed; /* This keeps the background fixed */ height: 100vh; /* Full viewport height */ width: 100%; }
How It Works:
background-attachment: fixedis the star here—it locks the background image to the viewport, so it won't scroll with the div itself.100vhensures the.main-bgdiv always takes up the entire height of the user's screen, regardless of their device or browser settings.- Resetting
marginandpaddingonbodyandhtmlremoves the tiny default gaps browsers add, so your full-screen div fits perfectly edge-to-edge.
Now when you scroll down, the fixed background will stay in place, and the red .after div will slide into view below it exactly as you wanted!
内容的提问来源于stack exchange,提问作者Ahsan Habib
相关产品推荐
相关产品推荐

