一個簡短的歷史,如果你愿意那樣說的話。
粘連 footer 的目的是讓它“支撐”在瀏覽器窗口的底部。但不總是在底部,如果有足夠的內容將頁面撐開,footer 可以被撐到網頁下方去。但是,如果頁面的內容很短,粘連 footer 仍然會出現在瀏覽器窗口的底部。
用一個元素將除了 footer 之外的其他內容包起來。給它設一個負的 margin-bottom,讓它正好等于 footer 的高度。這是一個最基本的方法( 例子 )。
例子: 用負 margin 粘連 footer
content
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 元素),這樣確保不會因為負 margin 將 footer 提升上來而覆蓋了任何實際內容。 .push 元素也最好不要有自己的 margin-bottom,如果有,那么它也得算在負 margin 中,而這又會使得 push 的 height 和 .wrapper 的 margin-bottom 的數字不一樣,看起來也不是很好。
用 這個 技術不需要一個 push 元素,但是相應地,在內容外面需要額外再包一層元素來讓它產生對應的 padding-bottom。這也是為了防止負 margin 導致 footer 覆蓋任何實際內容。
例子: 用負 margin 粘連 footer 2
content
html, body { height: 100%; margin: 0;}.content { min-height: 100%;}.content-inside { padding: 20px; padding-bottom: 50px;}.footer { height: 50px; margin-top: -50px;}
這個技術和前一個有一個同樣的缺點,就是它們都需要添加額外的 HTML 元素。
有一個不需要添加額外元素的 方法 ,那就是通過 cacl() 調整 wrapper 的高度。這樣不需要任何附加的元素,只需要兩個元素并排共用 100% 高度。
例子: Sticky Footer with calc();
content
.content { min-height: calc(100vh - 70px);}.footer { height: 50px;}
注意我這里用 calc() 扣除了 70px,把 footer 固定為 50px。這是假設內容中的最后一個元素有一個 20px 的 margin-bottom。這個 margin-bottom 和 footer 的高度要加在一起從 viewport 高度中扣除。而且,我們在這里還用了 viewport 單位( vh ——譯者注),這是另外一個小技巧,能夠避免在讓 wrapper 高度為 100% 時還得先把 body 高度設為 100%。
上面三種技術的大問題是它們需要 footer 的高度固定。Web 設計中固定高度通常都不好。內容可能改變。我們需要靈活性。固定高度通常要被亮紅燈。 使用 flexbox 來實現粘連 footer 不僅不需要任何額外的元素,還可以支持 footer 可變高度。
例子: 用 Flexbox 粘連 Footer
content
html { height: 100%;}body { min-height: 100%; display: flex; flex-direction: column;}.content { flex: 1;}
你甚至可以添加一個 header 到 .content 前面或者其他更多內容到后面。使用 flexbox 的訣竅是:
記得我們有一個關于一切 flexbox 相關內容的 完整的指南 。
Grid 布局是一種更新的技術(目前 支持它的瀏覽器比 flexbox 更少 )。我們也有一個關于它的 完整的指南 。用它實現粘連 footer 也相當容易。
例子: 用 Grid 粘連 footer
content
html { height: 100%;}body { min-height: 100%; display: grid; grid-template-rows: 1fr auto;}.footer { grid-row-start: 2; grid-row-end: 3;}
這個例子只能在 Chrome Canary 或者 Firefox 開發版上工作,并且可能在 Edge 下被降級到舊的 grid 布局版本。
英文原文: https://css-tricks.com/couple-takes-sticky-footer/
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com