[原文连接 - http://t.cn/RJ3nmhV )css
页脚置底(Sticky footer)就是让网页的footer部分始终在浏览器窗口的底部。html
当网页内容足够长以致超出浏览器可视高度时,页脚会随着内容被推到网页底部;
但若是网页内容不够长,置底的页脚就会保持在浏览器窗口底部。浏览器
margin-bottom
设为负数<div class="wrapper"> <!-- content --> <div class="push"></div> </div> <div class="footer">footer</div>
html, body { margin: 0; padding: 0; height: 100%; } .wrapper { min-height: 100%; margin-bottom: -50px; /* 等于footer的高度 */ } .footer, .push { height: 50px; }
这个方法须要容器里有额外的占位元素(div.push
)。app
div.wrapper
的margin-bottom
须要和div.footer
的-height
值同样,注意是负height
。ide
margin-top
设为负数给内容外增长父元素,并让内容部分的padding-bottom
与页脚的height
相等。布局
<div class="content"> <div class="content-inside"> <!-- content --> </div> </div> <div class="footer">footer</div>
html, body { margin: 0; padding: 0; height: 100%; } .content { min-height: 100%; } .content-inside { padding: 20px; padding-bottom: 50px; } .footer { height: 50px; margin-top: -50px; }
calc()
设置内容高度<div class="content"> <!-- content --> </div> <div class="footer">footer</div>
.content { min-height: calc(100vh - 70px); } .footer { height: 50px; }
这里假设div.content
和div.footer
之间有20px的间距,因此70px=50px+20pxflex
以上三种方法的footer高度都是固定的,若是footer的内容太多则可能会破坏布局。flexbox
<div class="content"> <!-- content --> </div> <div class="footer">footer</div>
html { height: 100%; } body { min-height: 100%; display: flex; flex-direction: column; } .content { flex: 1; }
<div class="content"> <!-- content --> </div> <div class="footer">footer</div>
html { height: 100%; } body { min-height: 100%; display: grid; grid-template-rows: 1fr auto; } .footer { grid-row-start: 2; grid-row-end: 3; }