Sticky footer布局
最近发现公司的在内容较小的时候使用的是js,通过过去body以及内容高度对比,动态设置footer的position的属性来改变footer是否存在与底部。所以最近搜索了很多关于了sticky footer的布局。鉴于国内环境大多文章都是抄袭,很多内容都是没有只给了关键部分,都没有给了完整的配置,所以特地写了这篇文章仅供参考,如果文中有什么不妥的地方,请各位指出,我会尽量快的修改过来。
利用margin-top以及padding-bottom
这是一个兼容性比较好的方法,我个人也是比较推荐的,在pc以及移动端都有良好的表现。
css代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <style> html, body, p { margin: 0; padding: 0; }
.clearfix:after { display: block; content: ''; height: 0; visibility: hidden; clear: both; }
html, body { height: 100%; }
.wrapper { min-height: 100%; *height: 100%; background: red; }
.wrapper .content { padding-bottom: 100px; }
.footer { height: 100px; width: 100%; margin-top: -100px; background: hotpink; } </style>
|
html代码:
1 2 3 4 5 6 7 8 9 10
| <body> <div class="wrapper clearfix"> <div class="content"> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> </div> </div> <div class="footer"></div> </body>
|
执行效果自行复制代码实践,这个是经过我自己多次测试发现没有问题的。
利用flex布局实现
css代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <style type="text/css"> html, body, div, p{ margin: 0; padding: 0; } html{ height: 100%; } body{ min-height: 100%; display: flex; flex-direction:column; } .content{ flex: 1; } .footer{ width: 100%; height: 100px; background: hotpink; } </style>
|
html代码:
1 2 3 4 5 6 7 8
| <body> <div class="content"> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> </div> <div class="footer"></div> </body>
|
利用position实现
css代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <style> html, body, p { margin: 0; padding: 0; } html,body{ height: 100%; } .wrapper{ width: 100%; position: relative; min-height: 100%; *height: 100%; padding-bottom: 100px; box-sizing: border-box; background: red; } .footer{ width: 100%; height: 100px; position: absolute; bottom: 0; background: hotpink; } </style>
|
html代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <body> <div class="wrapper"> <div class="content"> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> <p>这是一个p标签</p> </div> <div class="footer"></div> </div> </body>
|
同样的,这里通过padding-bottom为底部留足空间,box-sizing:border-box是为了不让padding计算在内容里。
暂时只更新这么多,待我测试一下其他的方法,觉得可行之后,再更新出来。