css sticky footer經典佈局

什麼是sticky footer佈局?
通常指手機頁面中,當內容高度撐不滿一屏時,頁腳緊貼屏幕底部;當內容高度超過一屏時,頁腳緊隨其後。css

方法一:flex彈性盒子佈局

  1. 父容器container的display爲flex,並規定項目排列順序是縱向的
  2. content元素的flex爲1,即有多餘空間就增大
  3. footer定義一個高度

查看演示請狠狠地點擊:flex彈性盒子佈局實現sticky footerapp

<div class="container">
  <div class="content">內容</div>
  <div class="footer">頁腳</div>
</div>
body {
  margin: 0;
}
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}
.content {
  flex: 1;
  /*非必須*/
  width: 100%;
  height: 300px;
  line-height: 300px;
  text-align: center;
  color: #fff;
  font-size: 30px;
  font-weight: bold;
  background-color: #71a8da;
  /*非必須*/
}
.footer {
  height: 60px;
  /*非必須*/
  width: 100%;
  line-height: 60px;
  text-align: center;
  color: #fff;
  font-size: 30px;
  font-weight: bold;
  background-color: #f85f2f;
  /*非必須*/
}

方法二:padding-bottom+負margin-top

  1. 容器wrapper須要指定min-height爲100vh(vh:視窗高度)
  2. 內容寫在content容器裏,指定padding-bottom爲footer容器的高度
  3. footer指定高度和margin-top,而且margin-top爲高度的負值

查看演示請狠狠地點擊:padding-bottom+負margin-top實現sticky footer佈局

<div class="wrapper">
  <div class="content">內容</div>
</div>
<div class="footer">頁腳</div>
body {
  margin: 0;
}
.wrapper {
  width: 100%;
  min-height: 100vh;
}
.content {
  /*padding-bottom應等於footer的高度*/
  padding-bottom: 60px;
  /*非必須*/
  width: 100%;
  height: 400px;
  line-height: 400px;
  text-align: center;
  color: #fff;
  font-size: 30px;
  font-weight: bold;
  background-color: #71a8da;
  /*非必須*/
}
.footer {
  /*margin-top應等於footer高度的負值*/
  margin-top: -60px;
  height: 60px;
  /*非必須*/
  width: 100%;
  line-height: 60px;
  text-align: center;
  color: #fff;
  font-size: 30px;
  font-weight: bold;
  background-color: #f85f2f;
  /*非必須*/
}

提示:兩個/**非必須**/之間的部分不是實現sticky footer佈局的必要代碼,只是一些輔助樣式,能夠刪除flex

相關文章
相關標籤/搜索