#筆記 簡單使用flex與sticky footer方式解決底部固定在底欄的問題

問題
許多大型網站都有一個底欄,不論內容的高度是否填滿屏幕,底欄都一直在頁面的最底部。

這個效果看似簡單,卻有不少的“坑”,下面我來介紹兩種方法解決這個問題。
第一個方法(引用中註釋的css)使用了固定定位解決
第二種方法使用的是flex佈局解決的
*具體請參考:<<css secret>> -41項 緊貼底部的頁腳*

要注意的是第一種方法必須設置外層容器的最小高度爲100%
第二種方法使用了flex屬性,flex包含三種屬性,這裏用到flex-grow: 設置放大比例

<!DOCTYPE html>
<html>

<head>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            background-color: #f3f3f3;
            height: 100%;
        }
        /*
        .container {
            position: relative;
            width: 100%;
            min-height: 100%;
        }

        .content {
            width: 100%;
            height: 600px;
            background: red;
        }

        .footer {
            height: 200px;
            width: 100%;
            background: yellow;
            position: absolute;
            bottom: 0;
        } */


        /*flex 佈局 */

        .container {
            display: flex;
            flex-direction: column;
            width: 100%;
            height: 100%;
        }

        .content {
            width: 100%;
            height: 600px;
            background: red;
            flex: 1 0 auto;
        }

        .footer {
            height: 200px;
            width: 100%;
            background: yellow;
            flex: 0 0 auto;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="content"></div>
        <div class="footer"></div>
    </div>
</body>

</html>

雖然兩種方法都能給我們達到最終的目的,但是在具體效果上還是有些區別
下面放幾張圖來對比一下。

這兩張圖片是flex方法的效果

由於內容受flex-grow: 1的影響,瀏覽器窗口的尺寸決定了content的尺寸。所以填充的顏色不受height屬性影響。

這張圖是sticky footer方式下的效果

sticky footer下的content的height屬性正常

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