1. 程式人生 > >兩種方式實現sticky footer絕對底部

兩種方式實現sticky footer絕對底部

gin 實現 add charset 什麽是 主體 ica min direction

一、什麽是sticky footer

如果頁面內容不夠長的時候,頁腳塊粘貼在視窗底部;如果內容足夠長時,頁腳塊會被內容向下推送,我們看到的效果就如下面兩張圖這樣。這種效果基本是無處不在的,很受歡迎。

技術分享

二、第一種方式,利用margin和padding實現

先看效果

技術分享

技術分享

下面是代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset=" utf-8">
    <title>margin,padding實現sticky footer</title>
    <
style> html, body, p { padding: 0; margin: 0; height: 100%; } body { min-height: 100%; } #wrapper { min-height: 100%; background: yellow; } #content { padding-bottom
: 50px; vertical-align: center; } #text-content{ height: 500px; } #footer { margin-top: -50px; height: 50px; background: wheat; } </style> </head> <body> <div id="wrapper"> <
div id="content"> <div id="text-content">填充內容11111111111111</div> </div> </div> <div id="footer">底部內容</div> </body> </html>

可以嘗試下在text-content中添加內容,可以發現,底部footer是不會受到影響的,堅挺的固定在底部。

這種套路的思路是,給內容區域設置 min-height: 100%,將 footer 推到屏幕下方

然後給 footer 添加 margin-top,其值為 footer 高度的負值,就能讓 footer 回到屏幕底部

需要註意的就是內容區域 content 的 padding、footer 的 height 和 margin, 必須保持一致

這種寫法的兼容性非常好,實測 IE7 也能正常展示

但是如果頁面的主體布局有其他兼容性問題,Sticky Footer 就需要做一些相應的修改

三、第三種方式,使用flex

技術分享

技術分享

代碼如下,沒有添加兼容性前綴

<!DOCTYPE html>
<html>
<head>
    <meta charset=" utf-8">
    <title>flex Sticky footer</title>
    <style>
        html, body {
            height: 100%;
            padding: 0;
            margin: 0;
        }

        body {
            min-height: 100%;
            display: flex;
            flex-direction: column;
        }

        #header {
            line-height: 50px;
            background: wheat;
        }

        #content {
            flex: 1;
            background: yellow;
        }

        #text-content {
            height: 600px;
        }

        #footer {
            line-height: 50px;
            background: wheat;
        }
    </style>

</head>
<body>
<div id="header">頂部</div>
<div id="content">
    <div id="text-content">aasdasd</div>

</div>
<div id="footer">底部</div>
</body>
</html>

這種方法就是利用flex布局對視窗高度進行分割。

footer的flex設為0,這樣footer獲得其固有的高度;

content的flex設為1,這樣它會充滿除去footer的其他部分。

兩種方式實現sticky footer絕對底部