在 UI 切图过程中,页面往往由三个部分组成,头部、内容和底部。当页面的内容高度不够撑满屏幕,底部(footer)就跟着内容浮动上来了,小屏幕由于高度有限看不出来异常,但如果是大屏的话,底部下面变会多出很多空白,非常影响美观。
方案 1:Flex-Box
头部使用 position: sticky; 吸顶,再使用盒子(main)来包住内容(container > content)和底部(footer),这个盒子设置最小高度为除头部外的剩余屏幕高度:min-height: calc(100vh - 50px);,盒子里面使用弹性布局(flex: 1 1 auto;)让内容区域自动撑开,而底部保持不变(flex: 0 0 auto;),这样就有了内容不够时底部自动吸底,内容足够时底部自动下移的效果。
示例:
CSS 实现底部(footer)贴底 - 方案 1:Flex-Boxbody {
margin: 0;
}
header {
height: 50px;
background: #20c997;
position: sticky;
top: 0;
}
main {
display: flex;
flex-flow: column nowrap;
min-height: calc(100vh - 50px);
}
.container {
flex: 1 1 auto;
}
.content {
background: #0d6efd;
}
footer {
flex: 0 0 auto;
background: #fd7e14;
}
header
content
footer
优点:底部高度可自由撑开。
缺点:低版本浏览器有兼容性(Flex-Box & Calc)问题。
方案 2:底部负距离 margin
内容区设置最小高度铺满页面,然后底部设置等高的负距离 margin。
示例:
CSS 实现底部(footer)贴底 - 方案 2:底部负距离 `margin`body {
margin: 0;
}
header {
height: 50px;
background: #20c997;
position: sticky;
top: 0;
}
.container {
min-height: calc(100vh - 50px);
}
.content {
background: #0d6efd;
}
footer {
height: 50px;
margin-top: -50px;
background: #fd7e14;
}
header
content
footer