頁腳固定底部

頁腳固定底部

今天遇到一個問題:使用css實現頁腳固定在底部,當內容不足一屏時,頁腳在窗口底部,當大於一屏時在整個頁面的最底部。總結兩種實現方式:css

第一種:html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>頁腳固定在頁面底部</title>
</head>
<style type="text/css">
    *{
        margin: 0;
        padding: 0;
    }
    html,body {
        height: 100%;
    }
    #container {
        min-height:100%;
        height: auto !important;
        height: 100%; /*IE6不識別min-height*/
        position: relative;
    }
    #content {
        width: 100%;
        height: 300px;
        margin: 0 auto;
        padding-bottom: 60px;/*等於footer的高度*/
    }
    header {
        background-color: #080808;
        height: 60px;
    }
    footer {
        position: absolute;
        bottom: 0;
        width: 100%;
        height: 60px;/*腳部的高度*/
        background-color: #080808;
        clear:both;
    }
</style>
<body>
<div id="container">
    <header>Header Section</header>
    <div id="content" class="clearfix">
        頁面容容部分
    </div>
    <footer>Footer Section</footer>
</div>
</body>
</html>
  1. 將html和body標籤中必須將高度(height)設置爲「100%」,這樣咱們就能夠在容器上設置百分比高度,同時須要將html,body的margin和padding都移除,也就是html,body的margin和padding都爲0。
  2. container容器必須設置一個最小高度(min-height)爲100%;這主要使他在內容不多(或沒有內容)狀況下,能保持100%的高度。
  3. content這個容器有一個很關鍵的設置,須要在這個容器上設置一個padding-bottom值,並且這個值要等於(或略大於)頁腳footer的高度(height)值。

第二種:瀏覽器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>頁腳固定在頁面底部</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        html,
        body{
            height: 100%;
            margin:0;
            padding:0;
        }
        #container {
            min-height: 100%;
            height: auto !important;
            height: 100%;
            margin: 0 auto -60px;/*margin-bottom的負值等於footer高度*/
        }
        header {
            height: 60px;
            background-color: #080808;
        }
        footer {
            height: 60px;
            clear:both;
            background-color: #080808;
        }
    </style>
</head>
<body>
<div id="container">
    <header>Header Section</header>
    <div id="page" class="clearfix">
        頁面容容部分
    </div>
</div>
<footer>Footer section</footer>
</body>
</html>

這種方法是利用footer的margin-top負值來實現footer永遠固定在頁面的底部效果。spa

這兩種方式結構簡單清晰,無需js和任何hack能實現各瀏覽器下的兼容。code

相關文章
相關標籤/搜索