You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现占屏幕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 100vh instead of 100% 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: fixed is the star here—it locks the background image to the viewport, so it won't scroll with the div itself.
  • 100vh ensures the .main-bg div always takes up the entire height of the user's screen, regardless of their device or browser settings.
  • Resetting margin and padding on body and html removes 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:03:20