您的位置:首页 > 其它

Keep your footer show at the bottom of the page

2014-07-15 15:10 190 查看
如何使网页的footer显示在页面最下方。这里讨论的不是让footer固定在viewport(或浏览器窗口)底部,而是页面的底部。具体来说分两种情况。

1. long page

When a page contains a large amount of content, the footer is pushed down off the viewport, and if you scroll down, the page ‘ends’ at the footer.

当页面包含大量内容,而且footer被自然地推到超出了viewport,当你滚动页面到下方,会自然地看到页面结束在footer。所以你不会注意到footer有什么不妥的地方。

此时你还没有对html,body,footer这些元素做任何position或是height 的修改。

2. short page

However, if the page has small amount of content, the footer can sometimes ‘cling’ to the bottom of the content, floating halfway down the page, and leaving a blank space underneath.

然而当页面只有很少内容的时候,footer是紧跟这页面实际内容的底部,你会看到footer出现在页面中且距离viewport底部有一大片空白。发现问题!

有时因为设计原因,这样的现象不是我们期待的。

3. possible solution

footer {
position: absolute;
bottom: 0;
width: 100%;
}
This usually ends up in it either overlapping (hiding) the bottom of the page content, or staying in the same position when the viewport is scrolled

单纯这样写,可以解决 short page 页脚的问题。

对于 long page 乍一看 footer 放置在浏览器的底部了,遮住页面靠近浏览器底部的内容,当页面向下滚动时, footer 一直被定在那个“初始”位置。本来没问题的 long page 现在出现问题

4. solution

此处 footer 的位置是相对于 html 而言(它的第一个父元素 body 此时 position 还是static 的,so 相对位置针对 html),我认为就是相对于浏览器窗口底部放置,当你不向下滚动页面,只改变窗口高度。效果同
position: fixed; bottom: 0; footer 随着窗口底部移动。

而当你向下滚动时,fixed 的页脚始终可见,如上设置 absolute 的页脚, 滚着滚着就滚上去看不见了。

这就是出现3里面 long page 问题的原因。添加以下代码:

body{
position: relative;
}
这样 footer 的相对放置位置为 body 元素的底部,在 long page 页脚就自然而然放置在页面结尾处,long page 问题解决 : )

但已经改好的 short page 又有问题了。

Many people assume that the <html> and <body> elements are always at least the height of the browser (min-height:100%). This is not the case: these elements, just like any other, will shrink to fit the least possible height, meaning that on pages with very
little content.

有些人认为 html、body 这些元素总是有至少和浏览器窗口一样高度,事实上,这些元素尽会收缩以符合尽可能小的高度。里面的实际内容撑起高度。

The space below is an empty void – nothing can be styled there or take up space there (apart from the background style of the <html> element, which most browsers recognise as needing to fill the screen.) 

在实际内容下面的空区域,只能设置 body 元素的 background 属性,任何其他元素都不能占据空间或被styled

What this means is that your footer can never be at the bottom of the browser window unless the <html> and <body> elements are at least 100% in height.

因此,对于 short page 只有 html、body 元素高度至少为100%时,footer才可能被放在底部。

添加以下代码

html{
height: 100%;
}
body{
min-height: 100%;
}
使文件可视化区域高度(body)至少达到浏览器窗口大小,这个添加改动对于 long page 是没有明显影响的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: