HTML/CSS

纯CSS粘住固定底部的5种方法

阿里云

本文主要介绍一个 Footer 元素如何粘住底部,使其无论内容多或者少,Footer 元素始终紧靠在浏览器的底部。我们知道,当内容足够多可以撑开底部到达浏览器的底部,如果内容不够多,不足以撑开元素到达浏览器的底部时,下面要讲的布局就是解决如何使元素粘住浏览器底部。需求看下图:

方法一:

全局增加一个负值下边距等于底部高度,有一个全局的元素包含除了底部之外的所有内容。它有一个负值下边距等于底部的高度,就像这个演示链接。

也想出现在这里?联系我们
创客主机
  1. <body>
  2.   <div class="wrapper">
  3.  
  4.       content
  5.  
  6.     <div class="push"></div>
  7.   </div>
  8.   <footer class="footer"></footer>
  9. </body>
  1. HTML, body {
  2.   height: 100%;
  3.   margin: 0;
  4. }
  5. .wrapper {
  6.   min-height: 100%;
  7.  
  8.   /* Equal to height of footer */
  9.   /* But also accounting for potential margin-bottom of last child */
  10.   margin-bottom: -50px;
  11. }
  12. .footer,
  13. .push {
  14.   height: 50px;
  15. }

演示:


这个代码需要一个额外的元素.push 等于底部的高度,来防止内容覆盖到底部的元素。这个 push 元素是智能的,它并没有占用到底部的利用,而是通过全局加了一个负边距来填充。

方法二:

底部元素增加负值上边距,虽然这个代码减少了一个.push 的元素,但还是需要增加多一层的元素包裹内容,并给他一个内边距使其等于底部的高度,防止内容覆盖到底部的内容。

  1. <body>
  2.   <div class="content">
  3.     <div class="content-inside">
  4.       content
  5.     </div>
  6.   </div>
  7.   <footer class="footer"></footer>
  8. </body>
  1. html, body {
  2.   height: 100%;
  3.   margin: 0;
  4. }
  5. .content {
  6.   min-height: 100%;
  7. }
  8. .content-inside {
  9.   padding: 20px;
  10.   padding-bottom: 50px;
  11. }
  12. .footer {
  13.   height: 50px;
  14.   margin-top: -50px;
  15. }

演示:

方法三:

使用 calc()计算内容的高度

  1. <body>
  2.   <div class="content">
  3.     content
  4.   </div>
  5.   <footer class="footer"></footer>
  6. </body>
  1. .content {
  2.   min-height: calc(100vh - 70px);
  3. }
  4. .footer {
  5.   height: 50px;
  6. }

演示:


给 70px 而不是 50px 是为了为了跟底部隔开 20px,防止紧靠在一起。

方法四:

使用 flexbox 布局方式

  1. <body>
  2.   <div class="content">
  3.     content
  4.   </div>
  5.   <footer class="footer"></footer>
  6. </body>
  1. html {
  2.   height: 100%;
  3. }
  4. body {
  5.   min-height: 100%;
  6.   display: flex;
  7.   flex-direction: column;
  8. }
  9. .content {
  10.   flex: 1;
  11. }

演示:

方法五:

使用 grid 布局

  1. <body>
  2.   <div class="content">
  3.     content
  4.   </div>
  5.   <footer class="footer"></footer>
  6. </body>
  1. html {
  2.   height: 100%;
  3. }
  4. body {
  5.   min-height: 100%;
  6.   display: grid;
  7.   grid-template-rows: 1fr auto;
  8. }
  9. .footer {
  10.   grid-row-start: 2;
  11.   grid-row-end: 3;
  12. }

演示:


grid 早于 flexbox 出现,但并没有 flexbox 被广泛支持,你可能在 chrome Canary 或者 Firefox 开发版上才可以看见效果。

纯 CSS 粘住固定底部的 5 种方法

已有 557 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!