頁腳置底(Sticky footer)就是讓網頁的footer部分始終在瀏覽器窗口的底部。當網頁內容足夠長以至超出瀏覽器可視高度時,頁腳會隨着內容被推到網頁底部;但如果網頁內容不夠長,置底的頁腳就會保持在瀏覽器窗口底部。
1、將內容部分的底部外邊距設為負數
這是個比較主流的用法,把內容部分最小高度設為100%,再利用內容部分的負底部外邊距值來達到當高度不滿時,頁腳保持在窗口底部,當高度超出則隨之推出的效果。
<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)
需要注意的是.wrapper的margin-bottom值需要和.footer的負的height值保持一致,這一點不太友好。
2、將頁腳的頂部外邊距設為負數
既然能在容器上使用負的margin bottom,那能否使用負margin top嗎?當然可以。
給內容外增加父元素,並讓內容部分的底部內邊距與頁腳高度的值相等。
<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()設置內容高度
有一種方法不需要任何多余元素——使用CSS3新增的計算函數calc()
這樣元素間就不會有重疊發生,也不需要控制內外邊距了~
<body> <div class="content"> content </div> <footer class="footer"></footer> </body> .content { min-height: calc(100vh - 70px); } .footer { height: 50px; }
可能你會疑惑內容高度calc()中為什么減去70px,而不是footer的高度50px,因為假設倆元素有20px的間距,所以70px=50px+20px
不過,你不必在意這些~
4、使用flexbox彈性盒布局
以上三種方法的footer高度都是固定的,通常來說這不利於網頁布局:內容會改變,它們都是彈性的,一旦內容超出固定高度就會破壞布局。所以給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或在下面添加更多元素。可從以下技巧選擇其一:
flex : 1 使內容(如:.content)高度可以自由伸縮
margin-top: auto
5、使用Grid網格布局
grid比flexbox還要新很多,並且更佳很簡潔
<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; }
遺憾的是,網格布局(Grid layout)目前僅支持Chrome Canary和Firefox Developer Edition版本。
總結
其實頁腳置底的布局隨處可見,很多人也和我一樣覺得比較簡單,但可能只知其然罷了,偶然看到CSS-TRICKS上介紹頁腳置底的文章覺得不錯,遂譯之。