什么是Sticky footer布局?
前端开发中大部分网站,都会把一个页面分为头部区块、内容区块、页脚区块,这也是比较。每每底部都要求能固定在屏幕的底部,而非随着文档流排布。要实现的样式能够归纳以下:若是页面内容不够长的时候,页脚区块在屏幕的底部;若是内容足够长的时候,页脚区块会被内容向下推送。能够如下图展现Sticky footer实现的效果:css
在正常的文档流中,页面内容较少的时候,若是不作处理,页脚部分不是固定在视窗底部的。html
使用sticky footer布局达到了预期的效果,及时内容区较少,页脚区块也是固定在底部。前端
实现方式
首先构建简单的布局代码:浏览器
<body> <div class="content"></div> <div class="footer"></div> </body>
其中content为内容区。方法介绍。
1、为内容区域添加最小高度
这种方法重要用vh(viewpoint height)来计算总体视窗的高度(1vh等于视窗高度的1%),而后减去底部footer的高度,从而求得内容区域的最小高度。例如咱们能够添加以下样式:app
.content { min-height: calc(100vh-footer的高度) }
此方法须要知道footer的高度,若是高度不肯定此方法不推荐。content的高度也能够用百分比来表示。布局
2、flex布局方式
html代码:flex
body { display: flex; flex-flow: column; min-height: 100vh; } .content { flex: 1; } .footer{ flex: 0; }
这种方法就是利用flex布局对视窗高度进行分割。footer的flex设为0,这样footer得到其固有的高度;content的flex设为1,这样它会充满除去footer的其余部分。网站
2、负margin布局方式实现
基本构架:
html代码spa
<div class="wrapper clearfix"> <div class="content"> // 这里是页面内容 </div> </div> <div class="footer"> // 这里是footer的内容 </div>
css代码:code
.wrapper { min-height: 100%; } .wrapper .content{ padding-bottom: 50px; /* footer区块的高度 */ } .footer { position: relative; margin-top: -50px; /* 使footer区块正好处于content的padding-bottom位置 */ height: 50px; clear: both; } .clearfix::after { display: block; content: "."; height: 0; clear: both; visibility: hidden; }
须要注意的:content元素的padding-bottom与footer元素的高度以及footer元素的margin-top值必需要保持一致。这种负margin的布局方式,是兼容性最佳的布局方案,各大浏览器都可完美兼容,适合各类场景,但使用这种方式的前提是必需要知道footer元素的高度,且结构相对较复杂。