您现在的位置是:网站首页> 编程资料编程资料

CSS Sticky Footer 几种实现方式

2023-10-19 231人已围观

简介 这篇文章主要介绍了CSS Sticky Footer 几种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

什么是 “Sticky Footer”

所谓 “Sticky Footer”,并不是什么新的前端概念和技术,它指的就是一种网页效果: 如果页面内容不足够长时,页脚固定在浏览器窗口的底部;如果内容足够长时,页脚固定在页面的最底部。但如果网页内容不够长,置底的页脚就会保持在浏览器窗口底部。

先来看看下面的例子, 代码如下

顶部

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

 .header { background-color: #3498DB; height: 50px; line-height: 50px; text-align: center; color: #fff; } .main { overflow: auto; box-sizing: border-box; } .footer { background-color: #ECF0F1; height: 50px; line-height: 50px; text-align: center; } 

细心读者应该发现问题了,底部 footer 位置会随着主体内容高度变化自动变化,当主体内容小于视口的高度时, footer 并没有黏贴在底部. 那么解决这样问题尼?

negative margin

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

中间部分

 html, body { height: 100%; } .header{ background-color: #3498DB; height: 50px; line-height: 50px; text-align: center; color: #fff; position: fixed; width: 100%; } .main { min-height: 100%; overflow: auto; box-sizing: border-box; padding-bottom: 50px; padding-top: 50px; margin-bottom: -50px; } .footer { background-color: #ECF0F1; height: 50px; line-height: 50px; text-align: center; } 

固定高度解决方案

使用如下属性

  • min-height
  • calc
  • vh

calc() 是 CSS3引入的,让你在声明CSS属性值时可以执行一些计算.

它可以用在一些数值场合; 详细可以查阅这里MDN

vh(Viewport Height): 顾明思议,表示的是视口的高度.

详细信息以及兼容可以查阅这里: caniuse

针对上面的代码进行修改,如下

 .main { min-height: calc(100vh - 50px - 50px); } 

这样完成我们期望的,但是有个缺点就是每次我们都要去计算 header、footer 的高度.

这显然不完美, 假如DOM结构层级多的话,需要计算的内容更多.

absolute

absolute相信大家熟悉不过了,这里就不在

-六神源码网