You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS Grid实现:让内容行占满屏幕,将Footer推至屏幕外

能否用纯HTML/CSS实现如下布局?

需求布局示意图:

|---------------------------| <-- 屏幕顶部
|          header           |   固定高度
|---------------------------|
|                           |
|                           |
|          content          |   填满剩余屏幕空间
|                           |
|                           |
|---------------------------| <-- 屏幕底部
|          footer           |   高度自适应
|---------------------------|

我尝试过相关方案但未解决问题,目前的代码实现如下:

body {
    width: 100%;
    min-height: 100%;
    margin: 0 0 0 0;
    background-color: gray;
}

.app-wrapper {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: auto 1fr auto;
    grid-template-areas: 
        "header header header header"
        "contnt contnt contnt contnt"
        "footer footer footer footer"
    ;

    height: 100vh;
    width: 100%;
}

.header {
    grid-area: header;
    background-color: lightcoral;
}

.content {
    grid-area: contnt;
    background-color: aqua;
}

.footer {
    grid-area: footer;
    background-color: lightyellow;
}
<body>
    <div class="app-wrapper">
        <div class="header">
            header
        </div>
        <div class="content">
            content
        </div>
        <div class="footer">
            footer
        </div>
    </div>
</body>

可行解决方案

你的代码框架已经正确,只需调整2个关键细节即可实现需求:

  1. 给body设置height: 100vh,替代原有的min-height: 100%,确保视口高度计算准确
  2. 将grid-template-rows中header对应的auto改为固定高度(比如80px),匹配你需求里的「固定高度」要求

修改后的完整代码:

body {
    width: 100%;
    height: 100vh;
    margin: 0;
    background-color: gray;
}

.app-wrapper {
    display: grid;
    grid-template-columns: 1fr; /* 单列布局无需4列设置,简化代码 */
    grid-template-rows: 80px 1fr auto; /* header固定高度,content占剩余空间,footer自适应 */
    grid-template-areas: 
        "header"
        "contnt"
        "footer";
    height: 100%;
    width: 100%;
}

.header {
    grid-area: header;
    background-color: lightcoral;
}

.content {
    grid-area: contnt;
    background-color: aqua;
}

.footer {
    grid-area: footer;
    background-color: lightyellow;
}
<body>
    <div class="app-wrapper">
        <div class="header">
            header
        </div>
        <div class="content">
            content
        </div>
        <div class="footer">
            footer
        </div>
    </div>
</body>

核心原理

  • grid-template-rows: 80px 1fr auto:明确分配行高,第一行固定高度,第二行用1fr占据容器剩余所有空间,第三行随内容自动调整高度
  • 容器和body都设置100%高度,确保网格容器填满整个视口
  • 简化列布局设置,避免不必要的多列声明

内容的提问来源于stack exchange,提问作者Angelo Orate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:33:29