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

如何用CSS实现header自适应、内容撑满视口、footer需滚动查看的布局

你只需要给绿色的Content区域添加flex: 1属性即可解决问题。在flex纵向布局的容器中,flex: 1会让对应子元素自动填充容器内的所有剩余空间,刚好匹配你的布局需求:

  • Header保持自身设定的高度,不会被压缩
  • Content自动占满.wrapper容器(高度为100vh)减去Header后的所有剩余空间,刚好拉伸到视口底部
  • Footer位于.wrapper之外,自然处于视口高度下方,用户需要滚动才能查看

修改后的完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }
        header {
            height: 5rem;
            padding: 2rem;
            background-color: cornflowerblue;
        }
        footer {
            background-color: crimson;
        }
        .wrapper {
            display: flex;
            height: 100vh;
            flex-direction: column;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <header>
            <h1>Header</h1>
        </header>
        <!-- 仅在原有基础上新增了flex:1属性 -->
        <div style="background-color: darkgreen; flex: 1">Content goes here.</div>
    </div>
    <footer>
        <h1>Footer</h1>
    </footer>
</body>
</html>

内容的提问来源于stack exchange,提问作者margherita pizza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:45:02