CSS五種方式實現(xiàn)Footer置底

https://css-tricks.com/couple-takes-sticky-footer/
頁腳置底(Sticky footer)就是讓網(wǎng)頁的footer部分始終在瀏覽器窗口的底部。
當(dāng)網(wǎng)頁內(nèi)容足夠長以至超出瀏覽器可視高度時,頁腳會隨著內(nèi)容被推到網(wǎng)頁底部;但如果網(wǎng)頁內(nèi)容不夠長,置底的頁腳就會保持在瀏覽器窗口底部。

sticky-footer-1.png

實現(xiàn)方法

1. 將內(nèi)容部分的底部外邊距設(shè)為負數(shù)

這是個比較主流的用法,把內(nèi)容部分最小高度設(shè)為100%,再利用內(nèi)容部分的負底部外邊距值來達到當(dāng)高度不滿時,頁腳保持在窗口底部,當(dāng)高度超出則隨之推出的效果。

<body> 
  <div class="wrapper"> 
    content 
    <div class="push"></div> 
  </div> 
  <footer class="footer"></footer>
</body>
html, body { height: 100%; margin: 0;}
.wrapper {
  min-height: 100%; /* 等于footer的高度 */ 
  margin-bottom: -50px;}
.footer,.push { height: 50px;}

這個方法需要容器里有額外的占位元素(如.push
需要注意的是.wrappermargin-bottom值需要和.footer的負的height值保持一致,這一點不太友好。

2. 將頁腳的頂部外邊距設(shè)為負數(shù)

既然能在容器上使用負的margin-bottom,那能否使用負margin-top嗎?當(dāng)然可以。
給內(nèi)容外增加父元素,并讓內(nèi)容部分的底部內(nèi)邊距與頁腳高度的值相等。

<body> 
  <div class="content"> 
    <div class="content-inside"> content </div> 
  </div>
  <footer class="footer"></footer>
</body>
html, body { height: 100%; margin: 0;}
.content { min-height: 100%;}
.content-inside { padding: 20px; padding-bottom: 50px;}
.footer { height: 50px; margin-top: -50px;}

不過這種方法和上一種一樣,都需要額外添加不必要的html元素。

3. 使用calc()設(shè)置內(nèi)容高度

有一種方法不需要任何多余元素——使用CSS3新增的計算函數(shù)calc()
這樣元素間就不會有重疊發(fā)生,也不需要控制內(nèi)外邊距了~

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

可能你會疑惑內(nèi)容高度calc()中為什么減去70px,而不是footer的高度50px,因為假設(shè)倆元素有20px的間距,所以70px=50px+20px
不過,你不必在意這些~

4. 使用flexbox彈性盒布局

以上三種方法的footer高度都是固定的,通常來說這不利于網(wǎng)頁布局:內(nèi)容會改變,它們都是彈性的,一旦內(nèi)容超出固定高度就會破壞布局。所以給footer使用flexbox吧,讓它的高度可以變大變小變漂亮~(≧?≦)

<body>
  <div class="content"> content </div> 
  <footer class="footer"></footer>
</body>
html { height: 100%;}
body { min-height: 100%; display: flex; flex-direction: column;}
.content { flex: 1;}

你還可以在上面添加header或在下面添加更多元素??蓮囊韵录记蛇x擇其一:flex: 1使內(nèi)容(如:.content高度可以自由伸縮margin-top: auto

請記住,我們有《Flexbox完整指南(英)》呢~

5. 使用Grid網(wǎng)格布局

grid比flexbox還要新很多,并且更佳很簡潔,我們同樣有《Grid完整指南(英)》奉上~

<body> 
  <div class="content"> content </div> 
  <footer class="footer"></footer>
</body>
html { height: 100%;}
body { min-height: 100%; display: grid; grid-template-rows: 1fr auto;}
.footer { grid-row-start: 2; grid-row-end: 3;}

遺憾的是,網(wǎng)格布局(Grid layout)目前僅支持Chrome Canary和Firefox Developer Edition版本。
總結(jié)
其實頁腳置底的布局隨處可見,很多人也和我一樣覺得比較簡單,但可能只知其然罷了,偶然看到CSS-TRICKS上介紹頁腳置底的文章覺得不錯,遂譯之。

原文鏈接:CSS五種方式實現(xiàn)Footer置底 Sticky Footer, Five Ways
原文作者:Chris Coyier
譯者:廖柯宇

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容