如何用Flex布局按10%/70%/20%高度划分Header/Container/Footer?
解决Flex布局下页面分区百分比高度不生效的问题
你的问题出在两个核心点:
- 百分比高度的依赖关系:CSS里百分比高度需要父元素有明确的高度值,你只给
body设了height:100%,但它的父元素<html>没有设置高度,导致body的100%高度无法基于视口计算。 - Flex布局属性误用:
body上的justify-content: center会让子元素垂直居中,破坏按比例分配高度的逻辑;align-content: space-between在flex-direction: column场景下无效,flex-wrap: wrap也完全没必要。
修改后的完整代码
* { box-sizing: border-box; padding: 0; margin: 0; } /* 给html和body都设置100%高度,让body的高度基于视口 */ html, body { height: 100%; width: 100%; } body { background-color: skyblue; display: flex; flex-direction: column; /* 保持垂直方向排列 */ } .header { display: flex; justify-content: center; align-items: center; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; background-color: black; color: rgb(225, 150, 0); font-weight: bold; font-style: italic; height: 10%; width: 100%; /* 新增:让header占满宽度 */ padding: 5px 10px; border: 1px solid blue; } .container { width: 100%; height: 70%; border: 1px solid red; /* 可选:如果想让container自动填充剩余空间,替换height:70%为flex:1 */ /* flex: 1; */ } .footer { width: 100%; height: 20%; border: 1px solid green; }
<div class="header"> <p>HEADER</p> </div> <div class="container"> <p>CONTAINER</p> </div> <div class="footer"> <p>FOOTER</p> </div>
关键修改说明
- 给
<html>添加height:100%,确保body的100%高度能正确继承到视口高度 - 清理
body上多余的Flex属性,只保留必要的display: flex和flex-direction: column - 给
.header补充width:100%,避免它只占内容宽度 - 如果你不想硬写70%的高度,也可以给
.container设置flex:1,让它自动填充Header和Footer之外的剩余空间,这种方式更灵活
内容的提问来源于stack exchange,提问作者milevicm
相关产品推荐
相关产品推荐

