将 footer 放在屏幕末尾
要求
- 当页面内容不够填充屏幕的时候,footer 显示在屏幕末尾;
- 当页面内容超出屏幕的时候,当页面滑到底时,footer 显示,位置也在屏幕末尾;

思路
- 在 content 和 footer 外创建一个 container,footer 放在 container 末尾;
- 当内容不够填充 viewport 的高度的时候,将 container 的高度设置为 viewport 的 100%,从而 footer 处于 container 的底部的同时,也处于 viewport 的底部;
- content 下面设置 padding ,留出一些空白,以免和 footer 重叠。
代码
See the Pen footer in bottom by Jason Zhou (@jasonzhouu) on CodePen.
解释
#footer设置position: absolute; bottom: 0px;表示,它脱离flow,并将位置放在 ancestor 的末尾。并且#page-container也要设置position: relative;。
position: absolutemeans something like “usetop,right,bottom,leftto position yourself in relation to the nearest ancestor who hasposition: absoluteorposition: relative.”
-
设置
position: absolute;后还得设置width: 100%;,否则无法占据屏幕宽度。 -
如果
#page-container不设置min-height: 100vh;,那么当内容不够填充 viewport 时,footer 将处于 viewport 中间:
-
如果
#page-container不设置min-height: 100vh;,而是设置height: 100vh,那么当#content-wrap的高度超出100vh时,则会溢出#page-container的边界,与#page-container底部的footer重叠。 -
#content-wrap设置padding-bottom: 2rem;,与#footer的 height 高度刚好吻合,从而不互相覆盖。否则,由于#footer脱离 flow,当#content-wrap足够填充整个 viewport 时,#content-wrap的底部将与#footer重叠。