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

如何设置HTML页面中Layout 3可滚动而Layout 2不可滚动?

问题:右侧分栏内部分内容可滚动,其余固定

我想要实现左右各占50%的固定分栏布局,已经编写了基础的分栏代码,现在需要让右侧区域中的.layout3部分在内容过长时可以滚动,而上方的.so(Layout2)保持固定不滚动。更新后的布局为:右侧分栏上方是固定内容区,下方是可滚动的长内容区。

现有代码

CSS 部分:

body {
    font-family: Arial;
}

.split {
    height: 100%;
    width: 50%;
    position: fixed;
    z-index: 1;
    top: 0;
    overflow-x: hidden;
}

.left {
    left: 0;
}

.right {
    right: 0;
}

HTML 部分:

<body>
    <div class="split left">
        .. content layout 1
    </div>
    <div class="split right">
        <div class="so">
            some content layout 2
        </div>
        <div class="layout3">
            .... long content ...
        </div>
    </div>
</body>

解决方案

通过Flex布局可以轻松实现这个需求,核心思路是让右侧分栏内部的元素垂直排列,固定上方内容,让下方内容占据剩余空间并开启滚动:

1. 修改右侧分栏的布局方式

给.right添加Flex布局,指定垂直排列方向:

.right {
    right: 0;
    display: flex;
    flex-direction: column;
}

2. 固定上方内容区(Layout2)

给.so设置样式,让它自适应内容高度(或固定高度),保持在顶部:

.so {
    /* 可选:设置固定高度,比如 height: 80px; */
    padding: 1rem;
    background-color: #f5f5f5;
    /* 禁止内部滚动(可选) */
    overflow: hidden;
}

3. 设置下方可滚动区域(Layout3)

给.layout3设置flex: 1让它占据右侧分栏的剩余高度,同时开启垂直滚动:

.layout3 {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
    background-color: #ffffff;
}

完整代码示例

CSS:

body {
    font-family: Arial;
    margin: 0; /* 清除默认边距,避免滚动条异常 */
}

.split {
    height: 100vh; /* 使用100vh确保占满视口高度 */
    width: 50%;
    position: fixed;
    z-index: 1;
    top: 0;
    overflow-x: hidden;
}

.left {
    left: 0;
    background-color: #e0e0e0; /* 示例背景色 */
}

.right {
    right: 0;
    display: flex;
    flex-direction: column;
}

.so {
    padding: 1rem;
    background-color: #f5f5f5;
}

.layout3 {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
    background-color: #ffffff;
}

HTML:

<body>
    <div class="split left">
        左侧固定内容区
    </div>
    <div class="split right">
        <div class="so">
            右侧固定内容区(Layout2)
        </div>
        <div class="layout3">
            <!-- 长内容示例 -->
            <p>长内容行 1</p>
            <p>长内容行 2</p>
            <p>长内容行 3</p>
            <p>长内容行 4</p>
            <p>长内容行 5</p>
            <p>长内容行 6</p>
            <p>长内容行 7</p>
            <p>长内容行 8</p>
            <p>长内容行 9</p>
            <p>长内容行 10</p>
            <p>长内容行 11</p>
            <p>长内容行 12</p>
            <p>长内容行 13</p>
            <p>长内容行 14</p>
            <p>长内容行 15</p>
            <p>长内容行 16</p>
            <p>长内容行 17</p>
            <p>长内容行 18</p>
            <p>长内容行 19</p>
            <p>长内容行 20</p>
        </div>
    </div>
</body>

原理说明

  • flex-direction: column让右侧分栏内的元素垂直排列
  • flex: 1让.layout3自动填充右侧分栏除.so之外的剩余空间
  • overflow-y: auto在.layout3内容超出高度时显示垂直滚动条,未超出时不显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:27:23