CSS粘住底部的5種方法


CSS粘住底部的5種方法

文章目錄

原文地址:https://css-tricks.com/couple-takes-sticky-footer/

譯文地址:http://caibaojian.com/css-5-ways-sticky-footer.html

譯者:前端開發博客-Jack

轉載請務必註明以上信息。

本文主要介紹一個Footer元素如何粘住底部,使其無論內容多或者少,Footer元素始終緊靠在瀏覽器的底部。我們知道,當內容足夠多可以撐開底部到達瀏覽器的底部,如果內容不夠多,不足以撐開元素到達瀏覽器的底部時,下面要講的佈局就是解決如何使元素粘住瀏覽器底部。需求看下圖:

原文來自http://caibaojian.com/css-5-ways-sticky-footer.html

方法一:全局增加一個負值下邊距等於底部高度

有一個全局的元素包含除了底部之外的所有內容。它有一個負值下邊距等於底部的高度,就像這個演示鏈接

html代碼

<body>
  <div class="wrapper">

      content

    <div class="push"></div>
  </div>
  <footer class="footer"></footer>
</body>

CSS代碼:

//code from http://caibaojian.com/css-5-ways-sticky-footer.html
html, body {
  height: 100%;
  margin: 0;
}
.wrapper {
  min-height: 100%;

  /* Equal to height of footer */
  /* But also accounting for potential margin-bottom of last child */
  margin-bottom: -50px;
}
.footer,
.push {
  height: 50px;
}

演示:

這個代碼需要一個額外的元素.push等於底部的高度,來防止內容覆蓋到底部的元素。這個push元素是智能的,它並沒有佔用到底部的利用,而是通過全局加了一個負邊距來填充。

方法二:底部元素增加負值上邊距

雖然這個代碼減少了一個.push的元素,但還是需要增加多一層的元素包裹內容,並給他一個內邊距使其等於底部的高度,防止內容覆蓋到底部的內容。

HTML代碼:

<body>
  <div class="content">
    <div class="content-inside">
      content
    </div>
  </div>
  <footer class="footer"></footer>
</body>

CSS

html, body {
  height: 100%;
  margin: 0;
}
.content {
  min-height: 100%;
}
.content-inside {
  padding: 20px;
  padding-bottom: 50px;
}
.footer {
  height: 50px;
  margin-top: -50px;
}

演示:

方法三:使用calc()計算內容的高度

HTML

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

.content {
  min-height: calc(100vh - 70px);
}
.footer {
  height: 50px;
}

演示:

給70px而不是50px是爲了爲了跟底部隔開20px,防止緊靠在一起。

方法四:使用flexbox

關於flexbox的教程,還請查看之前的一篇詳細的教程

HTML:

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

html {
  height: 100%;
}
body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
}

演示:

方法五:使用grid佈局

HTML:

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

html {
  height: 100%;
}
body {
  min-height: 100%;
  display: grid;
  grid-template-rows: 1fr auto;
}
.footer {
  grid-row-start: 2;
  grid-row-end: 3;
}

演示:

grid早於flexbox出現,但並沒有flexbox被廣泛支持,你可能在chrome  Canary或者Firefox開發版上纔可以看見效果

譯者注:本文並沒有全部參照原文來翻譯,更多是給出一個大體的思路,歡迎大家進入英文查看原鏈接。翻譯得不好,還請見諒。


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