Keep your footer show at the bottom of the page

如何使網頁的footer顯示在頁面最下方。這裏討論的不是讓footer固定在viewport(或瀏覽器窗口)底部,而是頁面的底部。具體來說分兩種情況。

1. long page

When a page contains a large amount of content, the footer is pushed down off the viewport, and if you scroll down, the page ‘ends’ at the footer.

當頁面包含大量內容,而且footer被自然地推到超出了viewport,當你滾動頁面到下方,會自然地看到頁面結束在footer。所以你不會注意到footer有什麼不妥的地方。

此時你還沒有對html,body,footer這些元素做任何position或是height 的修改。

2. short page

However, if the page has small amount of content, the footer can sometimes ‘cling’ to the bottom of the content, floating halfway down the page, and leaving a blank space underneath.

然而當頁面只有很少內容的時候,footer是緊跟這頁面實際內容的底部,你會看到footer出現在頁面中且距離viewport底部有一大片空白。發現問題!

有時因爲設計原因,這樣的現象不是我們期待的。

3. possible solution

footer {
  position: absolute;
  bottom: 0;
  width: 100%;
}
This usually ends up in it either overlapping (hiding) the bottom of the page content, or staying in the same position when the viewport is scrolled

單純這樣寫,可以解決 short page 頁腳的問題。

對於 long page 乍一看 footer 放置在瀏覽器的底部了,遮住頁面靠近瀏覽器底部的內容,當頁面向下滾動時, footer 一直被定在那個“初始”位置。本來沒問題的 long page 現在出現問題

4. solution

此處 footer 的位置是相對於 html 而言(它的第一個父元素 body 此時 position 還是static 的,so 相對位置針對 html),我認爲就是相對於瀏覽器窗口底部放置,當你不向下滾動頁面,只改變窗口高度。效果同 position: fixed; bottom: 0; footer 隨着窗口底部移動。

而當你向下滾動時,fixed 的頁腳始終可見,如上設置 absolute 的頁腳, 滾着滾着就滾上去看不見了。

這就是出現3裏面 long page 問題的原因。添加以下代碼

body{
  position: relative;
}
這樣 footer 的相對放置位置爲 body 元素的底部,在 long page 頁腳就自然而然放置在頁面結尾處,long page 問題解決 : )

但已經改好的 short page 又有問題了。

Many people assume that the <html> and <body> elements are always at least the height of the browser (min-height:100%). This is not the case: these elements, just like any other, will shrink to fit the least possible height, meaning that on pages with very little content.

有些人認爲 html、body 這些元素總是有至少和瀏覽器窗口一樣高度,事實上,這些元素盡會收縮以符合儘可能小的高度。裏面的實際內容撐起高度。

The space below is an empty void – nothing can be styled there or take up space there (apart from the background style of the <html> element, which most browsers recognise as needing to fill the screen.) 

在實際內容下面的空區域,只能設置 body 元素的 background 屬性,任何其他元素都不能佔據空間或被styled

What this means is that your footer can never be at the bottom of the browser window unless the <html> and <body> elements are at least 100% in height.

因此,對於 short page 只有 html、body 元素高度至少爲100%時,footer纔可能被放在底部。

添加以下代碼

html{
  height: 100%;
}
body{
  min-height: 100%;
}
使文件可視化區域高度(body)至少達到瀏覽器窗口大小,這個添加改動對於 long page 是沒有明顯影響的。


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