首页 > 开发 > CSS > 正文

CSS实现Sticky Footer的示例代码

2024-07-11 08:31:57
字体:
来源:转载
供稿:网友

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

实现

方法

1. 将内容部分的底部外边距设为负数

这是个比较主流的用法,把内容部分最小高度设为100%,再利用内容部分的负底部外边距值来达到当高度不满时,页脚保持在窗口底部,当高度超出则随之推出的效果。

<body> <div class="wrapper"> content <div class="push"></div> </div> <footer class="footer"></footer></body>html, body { height: 100%; margin: 0;}.wrapper { min-height: 100%; /* 等于footer的高度 */ margin-bottom: -50px;}.footer,.push { height: 50px;}

这个方法需要容器里有额外的占位元素(如.push)

需要注意的是.wrapper的margin-bottom值需要和.footer的负的height值保持一致,这一点不太友好。

2. 将页脚的顶部外边距设为负数

既然能在容器上使用负的margin bottom,那能否使用负margin top吗?当然可以。

给内容外增加父元素,并让内容部分的底部内边距与页脚高度的值相等。

<body> <div class="content"> <div class="content-inside"> content </div> </div> <footer class="footer"></footer></body>html, body { height: 100%; margin: 0;}.content { min-height: 100%;}.content-inside { padding: 20px; padding-bottom: 50px;}.footer { height: 50px; margin-top: -50px;}

不过这种方法和上一种一样,都需要额外添加不必要的html元素。

3. 使用flexbox弹性盒布局

以上三种方法的footer高度都是固定的,通常来说这不利于网页布局:内容会改变,它们都是弹性的,一旦内容超出固定高度就会破坏布局。所以给footer使用flexbox吧,让它的高度可以变大变小变漂亮~(≧∇≦)

<body> <div class="content"> content </div> <footer class="footer"></footer></body>html { height: 100%;}body { min-height: 100%; display: flex; flex-direction: column;}.content { flex: 1;}

你还可以在上面添加header或在下面添加更多元素。可从以下技巧选择其一:

    flex: 1 使内容(如:.content)高度可以自由伸缩 margin-top: auto

请记住,我们有《Flexbox完整指南(英) 》呢~

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表