以下 HTML 很简单,可以满足我的要求。生坯向下伸展以填充窗口。
<body style="margin:0">
<div style="height:100%;display:flex;flex-direction:column">
<div style="background:#d0d0ff">
This is a header
</div>
<div style="background:#d0ffd0;flex-grow:1">
This is the body.
</div>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
但是,如果我用一些 flex 列替换该正文文本,并且我给它们height:100%是因为我希望它们拉伸到底部,newdiv实际上它的高度会大于其容器的 100% 并导致所有内容滚动。为什么这里的 100% 不是 100%?
<body style="margin:0">
<div style="height:100%;display:flex;flex-direction:column">
<div style="background:#d0d0ff">
This is a header
</div>
<div style="background:#d0ffd0;flex-grow:1">
<!-- The new part -->
<div id='newdiv' style="display:flex;flex-direction:row; height:100%">
<div style="background:#ffd0d0"> Col 1 </div>
<div> Col 2 </div>
</div>
</div>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
您获得垂直滚动条的原因是因为您告诉col1和的 div 父级col2是height: 100%。这本身就给出了视口的完整高度。
从你的代码:
<div id='newdiv' style="display:flex; flex-direction:row; height:100%">
<div style="background:#ffd0d0"> Col 1 </div>
<div> Col 2 </div>
</div>
Run Code Online (Sandbox Code Playgroud)
除了这个 div 有一个兄弟:标题 div,它也占用空间。
因此,当浏览器进行高度计算时,结果如下:
100% + (computed height of header div) > viewport height = vertical scrollbar
Run Code Online (Sandbox Code Playgroud)
考虑让 Flexbox 来完成这项工作,而不是使用定义的高度。默认情况下,弹性项目沿横轴扩展容器的整个长度。
因此,通过简单地声明display: flex,子元素将扩展以填充所有可用空间(没有垂直滚动)。但由于height规则将覆盖此弹性设置,因此我们需要height: 100%从任何弹性项目中删除。
<div id='newdiv' style="display:flex; flex-direction:row; height:100%">
<div style="background:#ffd0d0"> Col 1 </div>
<div> Col 2 </div>
</div>
Run Code Online (Sandbox Code Playgroud)
100% + (computed height of header div) > viewport height = vertical scrollbar
Run Code Online (Sandbox Code Playgroud)
对原来的代码有两处调整。
display: flexheight: 100%