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

如何让容器可滚动同时保持标题部分显示在容器外

解决方案

问题原因

给.box添加overflow-y: scroll后,容器会裁剪所有超出自身范围的子元素——哪怕是绝对定位的<h1>也会被隐藏,这就是标题显示异常的原因。

修复方案

方案1:将标题移出滚动容器

把<h1>从.box里单独拿出来,调整布局参数让它保持原位置,同时让.box内部内容独立滚动:

<style>
h1 {
    font-family: swirlgarden;
    font-size: 55px;
    text-align: center;
    color: #3d729e;
    margin-top: -50px; /* 调整数值匹配你想要的位置 */
}
.box {
    position: relative;
    width: 950px;
    height: 700px;
    background-color: #fffaf0;
    border: 5px solid orange;
    margin: auto;
    margin-top: 100px;
    overflow-y: scroll;
    padding-top: 20px; /* 可选,给内部内容留顶部空间 */
}
</style>

<h1>Summer Knowledge</h1>
<div class="box">
    <!-- 这里放置需要滚动的长内容 -->
    <p>示例滚动内容...</p>
    <!-- 更多内容 -->
</div>

方案2:嵌套滚动容器(保留标题在父容器内)

如果不想移动<h1>,可以给.box内部新增一个专门的滚动容器,让标题处于容器外部不受overflow影响:

<style>
h1 {
    font-family: swirlgarden;
    font-size: 55px;
    text-align: center;
    color: #3d729e;
    position: absolute;
    top: -150px;
    width: 100%; /* 确保标题在容器宽度内居中 */
}
.box {
    position: relative;
    width: 950px;
    margin: auto;
    margin-top: 100px;
}
.scroll-container {
    height: 700px;
    background-color: #fffaf0;
    border: 5px solid orange;
    overflow-y: scroll;
}
</style>

<div class="box">
    <h1>Summer Knowledge</h1>
    <div class="scroll-container">
        <!-- 这里放置需要滚动的长内容 -->
        <p>示例滚动内容...</p>
    </div>
</div>

说明

两种方案都能实现你要的效果:标题显示在盒子外部,盒子内部内容可垂直滚动,根据你的布局习惯选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:22:45