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

NextJS中实现固定网格背景且内容可滚动的方案咨询

解决NextJS中网格背景固定且内容可滚动的问题

问题出在你给body设置了position: fixed,这会让整个页面固定,导致内容无法滚动。下面提供两种简单的解决方案:

方案一:使用独立背景层(推荐,更灵活)

将背景从body分离到一个独立的全屏固定div中,让body恢复默认滚动行为:

修改后的JSX结构

<body>
  {/* 独立的固定背景层 */}
  <div className="bg"></div>
  
  <motion.div
    className="outer-circle"
    variants={variants}
    animate={cursorVariant}
  >
    <div className="cursor"></div>
  </motion.div>
  
  <NavBar />
  <div className="max-w-[1000px] mx-auto py-2 px-3 mt-5">{children}</div>
</body>

保持原CSS不变

.bg {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
  background-color: #f3f3f3;
  background-image: linear-gradient(
      to right,
      rgba(223, 223, 223, 0.6) 1px,
      transparent 1px
    ),
    linear-gradient(to bottom, rgba(223, 223, 223, 0.6) 1px, transparent 1px);
  background-size: 100px 100px;
}

方案二:直接给body设置固定背景(更简洁)

利用background-attachment: fixed属性让背景固定,无需额外DOM元素:

修改后的CSS

body {
  background-color: #f3f3f3;
  background-image: linear-gradient(
      to right,
      rgba(223, 223, 223, 0.6) 1px,
      transparent 1px
    ),
    linear-gradient(to bottom, rgba(223, 223, 223, 0.6) 1px, transparent 1px);
  background-size: 100px 100px;
  background-attachment: fixed;
}

修改后的JSX结构

<body>
  <motion.div
    className="outer-circle"
    variants={variants}
    animate={cursorVariant}
  >
    <div className="cursor"></div>
  </motion.div>
  
  <NavBar />
  <div className="max-w-[1000px] mx-auto py-2 px-3 mt-5">{children}</div>
</body>

两种方案都能实现背景固定在视口,内容正常滚动的效果,可根据需求选择。

内容的提问来源于stack exchange,提问作者Santhosh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:50:27