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

无法通过z-index实现HTML元素层级与滚动效果的正确叠加

解决方案:调整堆叠上下文与z-index

核心修改逻辑

你的问题源于元素堆叠层级的冲突,通过明确设置position和z-index可以解决,最终要实现的层级顺序(从下到上)为:Block C → 绿色元素(SVG) → Block B,同时保证深绿色Block A容器与内部内容层级一致。

具体代码修改

return (
  <div className="h-[200vh] w-full flex flex-col items-center">
    {/* 深绿色Block A容器:添加z-10,与内部内容层级对齐 */}
    <div className="relative mt-[300px] bg-green-900 w-full h-[200px] text-black text-center flex flex-col justify-between text-white z-10">
      <div className="relative z-10">
        Block A
      </div>
    </div>

    {/* SVG图片:设置z-10,处于Block B和Block C之间 */}
    <Image
      src={borderSvgTexture}
      className="relative h-auto w-full min-w-screen mt-[-5px] z-10"
      alt=""
    />

    {/* Block B容器:设置z-20,确保重叠时能遮挡Block C */}
    <div className="bg-blue-600 w-full h-[200px] mt-[-50px] relative z-20">
      <div className='mt-[100px] text-center'>Block B</div>
    </div>

    {/* Block C:设置z-0,明确层级低于其他元素 */}
    <motion.div
      style={{ y }}
      className="h-[500px] flex justify-center absolute inset-x-0 mx-auto max-w-[1800px] text-white z-0"
    >
      <div className="w-[100px] h-[100px] bg-red-500">Block C</div>
    </motion.div>
  </div>
)

关键说明

  1. 堆叠上下文:只有设置了position: relative/absolute/fixed/sticky的元素,z-index才会生效,因此给所有需要调整层级的元素添加relative(Block C本身是absolute,已满足)。
  2. 层级顺序:通过z-0、z-10、z-20的数值差,明确各元素的堆叠优先级,确保:
    • Block C滚动到Block B区域时,被Block B遮挡
    • SVG始终在Block B下方、Block C上方
    • Block A容器与内部内容同层级,不会出现内容被遮挡的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 23:47:02