如何实现可垂直拉伸的全屏布局?修复内容塌陷问题
我正在尝试创建一种全屏布局,使内容区域能够根据Footer的尺寸自动调整。
初始正常布局
以下布局中,修改.footer的height值时,内容区域会自动填充Footer之外的剩余空间,完全符合预期:
body { margin: 0; padding: 0; } .layout { height: 100vh; display: flex; flex-direction: column; background-color: yellow; } .layout__content { height: 100%; align-self: stretch; background-color: blue; } .content { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background-color: green; } .content__text { background-color: white; } .footer { height: 20vh; background-color: red; }
<div class='layout'> <main class='layout__content'> <div class='content'> <text class='content__text'>Here be dragons</text> </div> </main> <footer class='footer' /> </div>
需求升级与问题
现在需要实现:
- 当内容与Footer的总高度不超过100vh时,显示效果与上述布局一致;
- 若内容高度导致总高度超过100vh,则内容区域自动出现滚动条。
尝试修改.layout的height为min-height:100vh后,当内容文本设置为150vh时能触发滚动,但移除文本高度后,内容区域会塌陷:
body { margin: 0; padding: 0; } .layout { min-height: 100vh; display: flex; flex-direction: column; background-color: yellow; } .layout__content { height: 100%; align-self: stretch; background-color: blue; } .content { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background-color: green; } .content__text { background-color: white; } .footer { height: 20vh; background-color: red; }
<div class='layout'> <main class='layout__content'> <div class='content'> <text class='content__text'>Here be dragons</text> </div> </main> <footer class='footer' /> </div>
注意事项
- 仅允许修改
.layout和.layout__content的CSS属性; .footer高度不固定,无法在其他元素中硬编码与高度相关的数值。
我已尝试过以下方法但未解决问题:
.layout设置height: 1px;.layout__content设置min-height: inherit;.layout__content设置min-height: 100%;
解决方案
只需要修改.layout和.layout__content的两个关键属性即可实现需求:
.layout { min-height: 100vh; display: flex; flex-direction: column; background-color: yellow; } .layout__content { flex-grow: 1; align-self: stretch; background-color: blue; overflow: auto; }
原理说明
flex-grow:1:在flex垂直布局中,该属性会让.layout__content自动填充.layout中除Footer外的所有剩余空间,彻底解决内容区域塌陷问题;overflow:auto:当内容高度超过.layout__content的可用空间时,自动显示滚动条,同时不影响内容高度不足时的正常布局;.layout保留min-height:100vh,确保布局至少占满一屏,内容过长时整体高度自动扩展。
内容的提问来源于stack exchange,提问作者Michael Linker
相关产品推荐
相关产品推荐

