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

如何在网页指定区域实现堆叠滚动效果?

实现指定区域的堆叠滚动效果

要让container-2、container-3、container-4实现堆叠滚动效果,同时让其他区域保持正常滚动,核心是把需要堆叠的容器放到独立父容器中,利用sticky定位实现局部堆叠。以下是修改后的完整代码:

修改后的HTML代码

<!DOCTYPE html>
<html>
<head>
    <title>Random BS</title>
    <link href="styles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
    <div class="container">
        <h1 style="margin-top: 0;">
            Poyo
        </h1>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>

    <!-- 新增父容器包裹需要堆叠的三个容器 -->
    <div class="stack-container">
        <div class="container-2">
            <p>Paya </p>

            <h2 style="margin-top: 0; position: absolute; bottom: 0; right: 0;">
                Service
            </h2>
        </div>

        <div class="container-3">
            <h1 style="margin-top: 0; color: wheat; position: relative; top: 300px; left: 500px;">
                Random text
            </h1>
        </div>

        <div class="container-4">
            <h1 style="margin-top: 0;">
                Yet more random text
            </h1>
        </div>
    </div>

    <div class="container-5">
        <h1 style="margin-top: 0;">
            Once again random text
        </h1>
    </div>
</body>
</html>

修改后的CSS代码

html, body{
    margin: 0;
    /* 移除全局height:100%,避免限制页面高度 */
}

/* 正常滚动的容器样式 */
.container, .container-5 {
    min-height: 100vh;
    padding: 2rem;
    box-sizing: border-box;
}

/* 堆叠效果的父容器 */
.stack-container {
    height: 300vh; /* 三个子容器各占100vh,总高度设为300vh以提供滚动空间 */
    position: relative;
}

/* 堆叠容器的通用样式 */
.container-2, .container-3, .container-4 {
    position: sticky;
    top: 0;
    height: 100vh;
    padding: 2rem;
    box-sizing: border-box;
}

.container-2{
    background-color: antiquewhite;
}

.container-3{
    background-color: black;
}

.container-4{
    background-color: red;
}

.container-5{
    background-color: blue;
}

关键实现说明

  1. 独立滚动上下文:用stack-container包裹需要堆叠的容器,设置其高度为300vh(对应三个100vh的子容器),让该容器内部产生独立滚动空间,不影响页面其他区域。
  2. Sticky定位:给container-2/3/4设置position: sticky; top: 0;,滚动父容器时,每个容器会固定在父容器顶部,后续容器自然堆叠在前一个容器上方,形成堆叠滚动效果。
  3. 区分正常区域:container和container-5设置min-height:100vh保证占满视口,保持正常流式滚动,不受堆叠逻辑影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:05:07