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

如何实现网页占满全高 按比例分配区块高度且文字垂直居中

解决方法

核心思路

采用Flex纵向布局实现自适应占满视口,不需要给header、section、footer固定百分比高度,避免影响区块内的文字对齐效果。

具体修改步骤

  • 首先清除浏览器默认的边距,给body开启纵向Flex布局,用min-height: 100vh保证页面最小高度占满整个视口,内容超过视口高度时也能正常滚动
    html, body {
      height: 100%;
      margin: 0;
    }
    body {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
    }
    
  • 给中间的section区块添加flex: 1属性,让它自动填充header和footer之外的所有剩余高度
    section {
      display: flex;
      flex: 1;
    }
    
  • 若需要nav、article内部的内容垂直居中,可给两个元素增加弹性垂直居中配置:
    nav, article {
      display: flex;
      flex-direction: column;
      justify-content: center;
      /* 原有样式无需修改 */
    }
    

完整修改后代码

<style>
    * {
        box-sizing: border-box;
        border: 0;
        margin: 0;
        padding: 0;
    }
    
    html, body {
        height: 100%;
    }

    body {
        display: flex;
        flex-direction: column;
        min-height: 100vh;
    }

    header{
        background-color: blue;
        padding: 30px 0;
        text-align: center;
        font-size: 30px;
    }
     

    section {
        display: flex;
        flex: 1;
    }
   
    nav, article {
        border: solid 1px black;
        background-color: aqua;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    nav {
        flex: 1;
        padding: 20px;
        background-color: darkslateblue;
    }

    article {
        text-align: center;
        padding: 10px;
        flex: 4;
    }

    footer {
        border: solid 1px black;
        background-color: crimson;
        padding: 10px;
        text-align: center;
    }
</style>
</head>
<body>
    <header>hello!</header>
    <section>
        <nav>
            <ul>
                <li><a href="">1</a></li>
                <li><a href="">2</a></li>
                <li><a href="">3</a></li>
                <li><a href="">4</a></li>
            </ul>
        </nav>
        <article>
            <h2>hello</h2>
            <p>hello how are you?</p>
        </article>
    </section>
    <footer>this is footer</footer>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 22:45:06