sticky-footer固定底部佈局

我們在開發的過程中會碰到內容很少,然後底部沒有固定到底部的問題,因此,sticky-footer很關鍵。在這裏我推薦兩種方法

方法1:使用flex佈局,具體的可以看該目錄下的demo1,其主要原理就是利用改變flex主軸方向爲縱軸,內容部分設爲flex:1,就是佔主軸方向的剩下部分,即100vh-footer的高度(100vh相當於視圖高度,1vh=1%*視圖的高度),示例請看demo1.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>sticky-footer-demo1</title>
  <style>
    body {
      display: flex;
      flex-flow: column;
      min-height: 100vh;
      padding: 0;
      margin: 0;
    }
    .wrapper {
      flex: 1
    }
    .footer {
      /* flex爲0可寫可不寫,因爲.wrapper會佔減去footer剩下位置 */
      /* flex: 0; */
      height: 80px;
      background: pink;
      color: #000;
    }

  </style>
</head>
<body>
  <div class="wrapper">我是wrapper</div>
  <div class="footer">我是底部</div>
</body>
</html>

方法2 :就是把html,body高度設爲100%,wrapper部分設置成min-height:100%;然後給wrapper下的內容設置padding-bottom:footer的高度; 最後給footer設置margin-top:-footer的高度,相當於把footer往上拉了和footer一樣的高度,詳細示例請看demo2.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>sticky-footer-demo2</title>
  <style>
    body {
      margin: 0;
      padding: 0;
    }
    html,body{
      height: 100%;
    }
    body > .wrapper {
      min-height: 100%;
    }
    .content {
      padding-bottom: 90px;/*必須與footer的高度保持一致*/
      background: green;
    }
    .footer {
      position: relative;
      margin-top: -90px; /*相當於把footer向上拉了90px*/
      height: 90px;
      background: pink;
      }
      .clearfix {
        *zoom: 1;
      }
      .clearfix::after {
        content: '';
        display: block;
        height: 0;
        line-height: 0;
        visibility: hidden;
        clear: both;
      }
  </style>
</head>
<body>
  <div class="wrapper clearfix">
    <div class="content">我是內容</div>
  </div>
  <div class="footer">我是底部</div>
</body>
</html>

demo1和demo2的html文件我放在了github上,我在share文件內會經常更新我學習到的知識並整理歸類,share文件夾地址爲https://github.com/yangyankang/share/tree/master/css/sticky-footer

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章