Footer部分永远沉底

8次阅读

共计 1396 个字符,预计需要花费 4 分钟才能阅读完成。

那么如何将 Web 页面的“footer”部分永远固定在页面的底部呢?(注意了这里所说的是页脚 footer 永远固定在页面的底部,而不是永远固定在显示器屏幕的底部

就是当内容只有一点点时,Web 页面显示在浏览器底部,当内容高度超过浏览器高度时,Web 页面的 footer 部分在页面的底部,总而言之 Web 页面的 footer 部分永远在页面的底部,也就是,Footer 部分永远沉底

  • 方法

1. HTML 结构:

         <div id="container">
            <div class="content">
                <ul>
                    <li> 内容 </li>
                </ul>
                <div class="footer"></div>
            </div>
        </div>

2. CSS 代码:

        * {
            padding: 0;
            margin: 0;
            list-style: none;
        }

        html,
        body {height: 100%;}
        
        #container {
            height: 100%;
            background-color: red;
            overflow-x: hidden;
        }

        .content {
            position: relative;
            min-height: 100%;
            background-color: yellow;
            padding-bottom: 70px;
            box-sizing: border-box;
        }

        .footer {
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 70px;
            background-color: blue;
        }
        
         <div class="container">
            <div class="content">
                <ul>
                    <li> 内容 </li>
                </ul>
                <div class="footer"></div>
            </div>
        </div>
    • 原理
    1. <html> 和 <body> 标签 :html 和 body 标签中必须将高度(height) 设置为“100%”, 这样我们就可以在容器上设置百分比高度。同时需要将 html,body 的 margin 和 padding 都移除,也就是 html,body 的 margin 和 padding 都为 0。
    2. div#container 容器 :div#container 容器将高度(height) 设置为“100%”;overflow-x: hidden;,好让内容在 container 容器内滚动。
    3. div.content 容器 :div.content 容器必须设置一个最小高度(min-height) 为 100%,这主要使他在内容很少(或没有内容)情况下,能保持 100%的高度。另外我们还需要在 div.content 容器中设置一个 ”position:relative” 以便于里面的元素进行绝对定位。再有就是设置一个 padding-bottom 值,而且这个值要等于(或略大于)页脚 div.footer 的高度(height)值。
    4. div.footer 容器:div.footer 容器必须设置一个固定高度。div.footer 还需要进行绝对定位,并且设置 bottom:0,让 div.footer 固定在容器 div.content 的底部。这样就可以实现我们前面所说的效果,当内容只有一点时,div.footer 固定在屏幕的底部(因为 div.content 设置了一个 min-height:100%),当内容高度超过屏幕的高度,div.footer 也固定在 div.content 底部,也就是固定在页面的底部。
    正文完
     0