在 UI 切图过程中,页面往往由三个部分组成,头部、内容和底部。当页面的内容高度不够撑满屏幕,底部(footer)就跟着内容浮动上来了,小屏幕由于高度有限看不出来异常,但如果是大屏的话,底部下面变会多出很多空白,非常影响美观。

方案 1:Flex-Box

头部使用 position: sticky; 吸顶,再使用盒子( main )来包住内容( container > content )和底部( footer ),这个盒子设置最小高度为除头部外的剩余屏幕高度: min-height: calc(100vh - 50px); ,盒子里面使用弹性布局( flex: 1 1 auto; )让内容区域自动撑开,而底部保持不变( flex: 0 0 auto; ),这样就有了 内容不够时底部自动吸底,内容足够时底部自动下移 的效果。

示例:

<html>  <head>    <title>CSS 实现底部(footer)贴底 - 方案 1:Flex-Box</title>    <style>      body {        margin: 0;      }      header {        height: 50px;        background: #20c997;        position: sticky;        top: 0;      }      main {        display: flex;        flex-flow: column nowrap;        min-height: calc(100vh - 50px);      }      .container {        flex: 1 1 auto;      }      .content {        background: #0d6efd;      }      footer {        flex: 0 0 auto;        background: #fd7e14;      }    </style>  </head>  <body>    <!--头部-->    <header>      header    </header>    <main>      <div class="container">        <!--内容-->        <div class="content">          content        </div>      </div>      <!--底部-->      <footer>        footer      </footer>    </main>  </body></html>

在线演示: https://codepen.io/mazeyqian/pen/rNeymdG

优点:底部高度可自由撑开。

缺点:低版本浏览器有兼容性(Flex-Box & Calc)问题。

方案 2:底部负距离 margin

内容区设置最小高度铺满页面,然后底部设置等高的负距离 margin 。

示例:

<html>  <head>    <title>CSS 实现底部(footer)贴底 - 方案 2:底部负距离 `margin`</title>    <style>      body {        margin: 0;      }      header {        height: 50px;        background: #20c997;        position: sticky;        top: 0;      }      .container {        min-height: calc(100vh - 50px);      }      .content {        background: #0d6efd;      }      footer {        height: 50px;        margin-top: -50px;        background: #fd7e14;      }    </style>  </head>  <body>    <!--头部-->    <header>      header    </header>    <div class="container">      <!--内容-->      <div class="content">        content      </div>    </div>    <!--底部-->    <footer>      footer    </footer>  </body></html>

在线演示: https://codepen.io/mazeyqian/pen/eYZvjzr

到此这篇关于CSS 实现内容高度不够的时候底部(footer)自动贴底的文章就介绍到这了,更多相关CSS  底部自动贴底内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!

CSS 实现内容高度不够的时候底部(footer)自动贴底