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

如何为百分比高度的卡片头部div实现overflow滚动效果?

解决卡片头部overflow滚动效果(百分比单位)

问题出在你的mapHeader元素高度设置逻辑冲突:height:100%会让它占满父元素cartaCus的全部高度,max-height:70%因小于100%完全无法生效;同时父元素缺少布局上下文,导致overflow约束无法正常传递。

以下是仅用百分比单位的解决方案,在同一个div中实现滚动效果:

修改后的CSS代码

.cartaCus {
    width: 92% !important;
    height: 90% !important;
    /* 添加flex布局,确保子元素百分比高度基于父元素计算 */
    display: flex;
    flex-direction: column;
}

.h90 {
    height: 90%;
}

.mapHeader {
    overflow: auto;
    /* 直接设置为父元素高度的70%,明确高度限制 */
    height: 70%;
    width: 100%;
    background-image: url(./../../../assets/images/backgrounds/map.png);
    background-color: red;
    /* 可选:优化背景图显示 */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
.w100 {
    width: 100%;
}
.alic {
    display: flex;
    justify-content: center;
    align-items: center;
}
.carta {
    background-color: white;
    border-radius: 10px;
    width: 100%;
    box-shadow: 0px 0px 4px 0px rgb(0 0 0 / 22%);
}
html,
body {
    height: 100%;
}

body {
    margin: 0;
    font-family: Roboto, "Helvetica Neue", sans-serif;
    background-color: #dedede;
}
.h100 {
    height: 100%;
}

原HTML结构无需调整(可直接使用)

<div class="w100 h90">
    <div class="alic h100">
        <div class="carta cartaCus">
            <div class="mapHeader">
                <!-- 添加超出高度的内容即可触发滚动 -->
                <p>测试内容</p>
                <p>测试内容</p>
                <p>测试内容</p>
                <p>测试内容</p>
                <p>测试内容</p>
                <p>测试内容</p>
                <p>测试内容</p>
                <p>测试内容</p>
                <p>测试内容</p>
                <p>测试内容</p>
            </div>
        </div>
    </div>
</div>

关键修改说明

  • 给cartaCus添加display: flex; flex-direction: column;:建立flex布局上下文,让子元素的百分比高度能正确继承父元素的高度约束。
  • 将mapHeader的height:100%; max-height:70%;改为height:70%;:直接限制头部高度为父卡片的70%,当内部内容超过该高度时,overflow:auto会自动显示滚动条。
  • 可选背景图属性优化:让背景图在滚动区域内显示更合理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:25:36