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

*ngFor渲染列表时CSS overflow失效问题求助

解决div overflow-y:auto不生效的问题

你的问题核心是百分比高度未正确生效,导致设置了overflow-y:auto的容器被内容撑高,无法触发滚动。另外如果想实现标题固定、列表滚动的效果,布局也需要调整,下面给出具体解决方案:

原因分析

  • .modelSamples 使用了 height:60%,但百分比高度的生效依赖父元素(比如body、外层容器)有明确的高度值。如果父元素没有设置高度,这个60%会被忽略,容器会被内部内容撑到足够高,overflow自然不会触发。
  • 即使给 .sampleList 加max-height,如果外层容器高度不固定,也无法限制内容范围。

解决方案

方案1:让整个容器(含标题)滚动

改用vh单位(基于视口高度)替代百分比,或者确保父元素设置明确高度:

  1. 先给根元素设置高度(如果用百分比的话):
html, body {
  height: 100%;
  margin: 0;
}
  1. 修改 .modelSamples 的样式:
.modelSamples{
    overflow-y: auto;
    margin-top: 10px;
    margin-left: 10px;
    width: 30%;
    height: 60vh; /* 直接基于视口高度的60%,无需依赖父元素 */
    background-color: rgb(191 126 235 / 29%);
    z-index: 1;
    border-radius: 30px;
    box-sizing: border-box; /* 防止内边距/边框撑大容器 */
    padding: 0 15px; /* 可选,避免内容贴容器边缘 */
}

方案2:标题固定,列表单独滚动(更推荐)

用flex布局让列表区域自动填充容器剩余高度,只给列表加滚动:

修改后的完整CSS:

/* 确保根元素高度,或者直接给.modelSamples用vh单位 */
html, body {
  height: 100%;
  margin: 0;
}

.modelSamples{
    margin-top: 10px;
    margin-left: 10px;
    width: 30%;
    height: 60%; /* 或60vh */
    background-color: rgb(191 126 235 / 29%);
    z-index: 1;
    border-radius: 30px;
    box-sizing: border-box;
    padding: 20px 15px 15px;
    display: flex;
    flex-direction: column; /* 垂直排列子元素 */
}

#samplesTitle{
    display: flex;
    font-family: Oswald;
    width: 100%;
    justify-content: center;
    color: white;
    font-size: 2rem;
    padding-bottom: 15px;
    margin-top: 0; /* 去掉默认margin,用容器padding控制间距 */
}

.sampleList{
    overflow-y: auto;
    flex: 1; /* 自动填充容器剩余高度 */
}

#samples{
    display: flex;
    flex-direction: row;
    font-family: Oswald;
    color: white;
    font-size: 20px;
    margin-left: 20px;
    justify-content: space-between;
}

#sampleName, #samplePlay{
    padding-bottom: 10px;
}

#samplePlay{
    padding-right: 30px;
}

额外注意

  • 检查HTML代码中的多余闭合标签:你的代码里.sampleList内部多了一个</div>,需要修正,避免布局错乱:
<div class="modelSamples">
  <div id="samplesTitle">
    SAMPLES
  </div>
  <div class="sampleList">
    <div id="samples" *ngFor="let tape of sampeList">
      <div id="sampleName"> {{tape.name}} </div>
      <div id="samplePlay">
        <mat-icon> play_circle </mat-icon>
      </div>
    </div>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:10:43