内部div不尊重外部div的css最大高度

Pie*_*her 5 html css

我有三个 div:

  • 灰色的 div 是我的外部 div,它定义了高度
  • 绿色的div是一个可以滚动的div
  • 红色div,即内容

以下代码示例是我为复制问题而创建的最小示例。

.outside {
    max-height: 500px;

    background-color: gray;
}

.inside {
    overflow-y: scroll;
    height: 100%;

    background-color: green;
    margin-right: 100px;
}

.content {
    height: 2000px;

    background-color: red;
    margin-right: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<html>
    <body style="overflow-y: hidden">
        <div class="outside">
            <div class="inside">
                <div class="content"></div>
            </div>
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

虽然灰色 div 的 max-height 为500px,但绿色 div 获取红色 div 的高度,并且不会滚动内部内容。

当设置height: 100%为灰色 div 时,对于大于灰色 div 高度的内容,滚动将按预期工作。如果内容(红色 div)较小,我希望绿色 div 仅是其内容的高度。

jot*_*tin 2

有几种方法可以做到这一点(如前所述)。在某些情况下,在移动设备上使用视口高度可能会出现问题。不要使用 vh,而是将灰色容器变成 Flex 对象。

.outside {
    max-height: 500px;
    background-color: gray;
    /* make it a flex container */
    display: flex;
    flex-direction: column;
}

.inside {
    overflow-y: scroll;
    height: 100%;
    background-color: green;
    margin-right: 100px;
}

.content {
    height: 2000px;
    background-color: red;
    margin-right: 100px;
    /* make scrolling more obvious */
    background: repeating-linear-gradient(
    -55deg,
    #ff0000,
    #ff0000 10px,
    #cc0c0c 10px,
    #cc0c0c 20px
    );
}
Run Code Online (Sandbox Code Playgroud)
<html>
    <body>
        <div class="outside">
            <div class="inside">
                <div class="content"></div>
            </div>
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

小提琴: https: //jsfiddle.net/0fhga6vt/