Flexbox:div 忽略高度属性

ste*_*ste 7 html css flexbox

我正在用 flexbox 构建一个模态,它有两行设计:

|-------------------|
|          A        |
|-------------------|
|                   |
|         B         |
|                   |
|                   |
|-------------------|
Run Code Online (Sandbox Code Playgroud)

由于 A 和 B 都是模态的一部分,高度以百分比表示而不是以 px 表示,因此我使用 flexbox 来给 A 一个高度,然后让 B 用可选的滚动条填充其余空间(如果需要)。

为了实现这一点,我使用以下 html + css :

<div class="wrapper">
    <div class="A"></div>
    <div class="B"></div>
</div>

.wrapper {
    display: flex;
    flex-direction: colum;
    height: 100%;
}

.A {
    height: 70px;
    width: 100%;
}

.B {
    margin: 10px 20px 10px 20px;
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
}
Run Code Online (Sandbox Code Playgroud)

问题在于,根据 B 的内容,A 的高度会发生变化。有些内容固定为 70px,其他一些内容可能是 24px,如果我检查 css 规则,我可以看到高度是 24px,当我点击规则时,它会突出显示“height: 70px”代码行。

如果我删除包装器中的“display:flex”,高度对于任何类型的内容都保持正确,但 div B 会溢出模态并完全忽略规则“overflow-y:auto”。

我该如何解决这个问题?

LGS*_*Son 9

如果您flex: 0 0 70px;min-height: 0;或结合使用overflow: hidden,则应确保A始终保持 70 像素高。

第一个0flex-grow防止它增长,第二个0flex-shrink防止它收缩,min-height/overflow将允许它也小于它的内容,默认情况下它不是(min-height默认为auto,它阻止弹性项目小于其内容)。

最后一个70pxflex-basis,它是 Flexbox 版本height,我建议你改用它。

注意,你缺少一个ncolumflex-direction价值。

.wrapper {
    display: flex;
    flex-direction: column;
    height: 90vh;
    background: lightgray;
}

.A {
    flex: 0 0 70px;
    width: 100%;
    min-height: 0;
    background: lightblue;
}

.B {
    margin: 10px 20px 10px 20px;
    flex-grow: 1;
    overflow-y: auto;
    overflow-x: hidden;
    background: lightgreen;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
    <div class="A">A</div>
    <div class="B">B</div>
</div>
Run Code Online (Sandbox Code Playgroud)