HTML 中使 footer 始終處於頁面底部


通常在頁面中,需要使頁腳 footer 部分始終處於底部。當頁面高度不夠 100% 時, footer 處於頁面最底部,當頁面內容高於 100% 時,頁腳元素可以被撐到最底部。

方法一:絕對定位

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>旋轉六面體動畫</title>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        html {
            height: 100%
        }
        /* 這里footer的父元素為 body, 實際應用中,不一定要以body為父元素,只要確保footer的父元素的最小高度為100%就行 */
        body {
            position: relative;
            min-height: 100%;
            padding: 0;
            padding-bottom: 40px;
        }

        #footer {
            height: 40px;
            background: #eee;
            width: 100%;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="box">
        <h1>content</h1>
        <h1>content</h1>
        <h1>content</h1>
        <h1>content</h1>
        <h1>content</h1>
    </div>
    <footer id="footer">
        <p>footer footer footer</p>
    </footer>
</body>

</html>

方法二: flex 布局

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>footer</title>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        html {
            height: 100%
        }

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

        #header {
            height: 40px;
            background: red;
            flex: 0 0 auto;
        }

        #box {
            background: #eee;
            flex: 1 0 auto;
        }

        #footer {
            height: 40px;
            background: rgb(129, 129, 201);
            flex: 0 0 auto;
        }
    </style>
</head>

<body>
    <header id="header">
        header header header
    </header>
    <div id="box">
        <h1>content</h1>
        <h1>content</h1>
        <h1>content</h1>
        <h1>content</h1>
        <h1>content</h1>
    </div>
    <footer id="footer">
        <p>footer footer footer</p>
    </footer>
</body>

</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM