• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

在 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  底部自动贴底内容请搜索极客世界以前的文章或继续浏览下面的相关文章,希望大家以后多多支持极客世界!


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
CSS 中的六个重要选择器(三秒就可以记住)发布时间:2022-06-21
下一篇:
详解浮动元素引起的问题和解决办法发布时间:2022-06-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap