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

如何正确设置CSS中container元素的滚动条高度?

解决容器滚动条高度适配问题

问题核心在于.container设置height: 100%会继承.parent的完整高度,但.parent内部还有.header元素,导致.container超出父容器范围,滚动区域异常。

正确修改方案

利用Flex布局让.container自动占据剩余空间:

  1. 修改.parent的样式,将其改为弹性布局并设置垂直方向排列:
.parent {
    display: inline-flex; /* 替换原来的inline-block,保持inline特性同时启用flex */
    flex-direction: column; /* 子元素垂直排列 */
    text-align: left;
    height: 100%;
    border-radius: 0.4em;
    overflow: hidden;
    font-size: 1em;
    line-height: 1em;
    width: 300px;
}
  1. 修改.container的样式,去掉固定高度,改用flex: 1让它自动填充剩余空间:
.container {
  overflow-y: scroll;
  flex: 1; /* 占据父容器除header外的所有剩余空间 */
}

修改后的完整CSS代码

html, body, #root {
    height: 100%;
    overflow: hidden;
}

body {
    background-color: green;
}

#root {
    text-align: center;
    background-color: white;
    padding-top: 6px;
    padding-bottom: 6px;
    overflow: hidden;
    min-width: 320px;
}

.parent {
    display: inline-flex;
    flex-direction: column;
    text-align: left;
    height: 100%;
    border-radius: 0.4em;
    overflow: hidden;
    font-size: 1em;
    line-height: 1em;
    width: 300px;
}

.header {
    position: relative;
    height: 3em;
    display: flex;
    align-items: center;
    background-color: gray;
    box-shadow: 0 1px 2px black;
    z-index: 10;
}

.container {
  overflow-y: scroll;
  flex: 1;
}

这样修改后,.container会自动适配.parent中除去.header的剩余高度,滚动条只会出现在内容超出该区域时,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:10:02