如何优雅的使footer保持在页面的最底部

技巧2年前 隔壁老李于 2022-06-10 16:32:51 最后编辑

今天看到拓源的ZBlog群里有人问为什么纯净主题的footer不在最底部。

看了一下截图,发现是因为他的文章太少了,content部分不够多,于是在页面下方会留出部分的空白

如何优雅的使footer保持在页面的最底部  第1张

比较暴力的解决办法就是给主体部分加一个最小高度

比如:

section {
    min-height:1080px;
}

但是这种方法对自适应页面不太友好,于是改成:

section {
    min-height:100vh;
}

再优化一下,可以减去页头和页脚的高度:

section {
min-height: calc(100vh - 160px);
}

又或者用JS判断窗口高度使footer始终在底部

$(document).ready(function(){
    if($(document.body).height()<$(window).height()){
        $("footer").css({"position":"fixed","bottom":"0px"});
    }
})

那么还有比较优雅的方法吗?

早些年可能会用position绝对定位解决问题,比如:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
* {
    margin: 0;
    padding: 0
}
body, html {
    height: 100%;
}
.container {
    position: relative;
    padding-bottom: 150px; /*大于等于footer的高度*/
    width: 100%;
    min-height: 100%;
    box-sizing: border-box;
}
header {
    width: 100%;
    height: 100px;
}
section {
    width: 100%;
    height: 300px;
}
footer {
    position: absolute;
    width: 100%;
    height: 150px;
    left: 0;
    bottom: 0;
}
</style>
</head>

<body>
<div class="container">
  <header>header</header>
  <section>content</section>
  <footer>footer</footer>
</div>
</body>
</html>

但是现在,我可能更喜欢另一种方式——flex布局

flexbox是css3提供的一种新的布局模型,可以说用了就回不去了~~

像这样:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
* {
    margin: 0;
    padding: 0
}
html {
    height: 100%;
}
body {
    display: flex;
    flex-direction: column;
    height: 100%;
}
header {
    flex: 0 0 auto;
}
section {
    flex: 1 0 auto;
}
footer {
    flex: 0 0 auto;
}
</style>
</head>
<body>
<header>header</header>
<section>content</section>
<footer>footer</footer>
</body>
</html>

关于flexbox的基础知识,推荐阅读:阮一峰的Flex布局教程


本文由 @隔壁老李 于 2022-06-10 发布在 野路子博客,如无特别说明,本博文章均为原创,转载请保留出处。
评论 (3)
访客
zzzzzzz
纯小白不知道怎么用,添加在哪啊,有大神给详细的指教一下吗?
还有我用 拓源纯净主题 用本博主的高亮代码会有一部分代码非常暗,我调了半天也没用,换个主题就好,是什么因为啊
· 来自河南省信阳市 · 回复
隔壁老李
@zzzzzzz 可能CSS冲突
· 来自山东省青岛市 · 回复
留风
牛啊牛啊
· 来自广东省广州市海珠区 · 回复
Top