在項目中前端er會遇到這種需求,頁腳固定,這個固定指的是當內容較少時,頁腳固定在瀏覽器底部(這種情況我們會考慮position:fixed),當內容足夠多,瀏覽器視口高度小於內容高度時,頁腳固定資頁面內容頁面的底部(這時會發現position:fixed滿足不了需求)。

content內容較少

//html
<header> I am header</header>
<div class="content">內容高度低</div>
<footer></footer>


//css
footer {
    position: fixed;
    width: 100%;
    height: 60px;
    background: red;
    bottom: 0;
    left: 0;
}

demo

content內容足夠多,用fixed佈局會發現頁腳footer會覆蓋在內容上

//html
    <header> I am header</header>
    <div class="content">
        <p>test</p>
        ...<!--a lot of p here-->
        <p>test</p>
    </div>
    <footer></footer>


    //css
    footer {
        position: fixed;
        width: 100%;
        height: 60px;
        background: red;
        bottom: 0;
        left: 0;
    }

demo

很明顯這不是我們想要的,解決上面的問題,我們需要用到”sticky footer”。

sticky footer應用場景是:當內容足夠少時,頁腳會固定在瀏覽器底部,當內容足夠多時,頁腳會固定在頁面底部,這裏的足夠少和足夠多也就是內容區的高度相對瀏覽器或者視口的高度比較而言。
實現sticky footer的方式有很多種,本文介紹一種常用的方法,或者説是通用方法。

內容較少

//html
<body>
<div class="container">
    <header> I am header</header> 
    <div class="content">
        <p>test</p>
        <p>test</p>
        <p>test</p>
    </div>
</div>
<footer>footer</footer>
</body>

//css
html,body {
        height: 100%;
        margin: 0;
        padding:0;
    }
    header {
        background: green;
    }
    .container {
        min-height: 100%;
        height: auto;
        overflow: auto;
    }
    .content {
        padding-bottom: 60px;
    }
    footer {
        position: relative;
        width: 100%;
        height: 60px;
        margin-top: -60px;
        background: red;
        clear: both;
    }

demo

這裏的關鍵是設置
1)html,body的height為100%,margin padding為0,如果html,body的高度沒有設置為100%,那麼就無法實現這樣的效果(可以自己嘗試)。
2)header和content用一個容器container div包裹,設置容器的min-height為100%,height:auto。
3)設置content的padding-bottom,主要一定不能寫成margin-bottom

這裏值得注意的是如果container容器只有content div需要設置overflow:auto,否則即使內容很少,也會出現滾動條,所以無論container是否只有content內容,一般都設置overflow:auto,這樣可以避免出現滾動條。

content裏面有很多內容,比如有很多p段落。這時footer沒有固定在視口的底部,而是固定在頁面的底部。

demo