如何将文本绝对定位到页面底部而不是视口?

3

我有一个页面,页脚上有:

postion: absolute;
bottom: 0;

当窗口高度大于内容时,它能够正常工作,但是当窗口高度小于内容时,页脚会出现在文本上方。我尝试过放置...
body {
    min-height: 550px;
}

但这并不能解决问题,我可以滚动,但页脚与视口底部对齐,(在安卓上,当我滚动时,页脚会改变到窗口底部)。
是否可能在有滚动条时将页脚对齐到页面底部?
这是我的页面

必须使用绝对定位吗?如果您删除绝对定位并将页脚放置在标记的末尾,它将定位在内容底部 - 即使内容超出视口。 - Danield
1
在你的 body 中添加 position:relative:http://jsfiddle.net/KjBFu/ ? - Passerby
@Passerby 非常感谢,它起作用了,请将其添加为答案,我会接受它。 - jcubic
2个回答

4
<body> 添加 position:relative 属性,使页脚相对于 <body> 定位,而不是相对于 <html> 或视口:
body {
    position:relative;
}

请查看此jsfiddle,使用“toggle”按钮在相对定位和静态定位之间切换<body>,并观察其不同之处。
这是因为position:absolute元素的位置是基于最深层父元素的位置的。来自MDN的解释如下:

定位元素是计算出的位置属性为 relative, absolute, 或 fixed 的元素。


1
如果我理解正确的话。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS Layout Example</title>
<style type="text/css">
html, body { 
    margin:0; padding:0; 
    height:100%; 
    font-size:12px; font-family:Verdana, Geneva, sans-serif; 
}

.container { width:900px; position:relative; margin:0 auto; }
.body { min-height:100%; position:relative; }

/**
 * padding-bottom -> the "computed" height of the footer (height + padding).
 * In this example 20 + 10 + 10 = 40 (height + padding-top + padding-bottom)
 */
.main { padding-bottom:40px; }

.header { background-color:#006600; color:#FFFFFF; margin-bottom:10px; padding:10px; }
.page { background-color:#CCCCCC; padding:10px; }

.footer { position:absolute; bottom:0; display:block; width:100%; z-index:1000; }
.footer .container { 
    background-color:#000000; color:#FFFFFF; 
    padding:10px; height:20px; 
}

</style>
</head>

<body><div class="body">
    <div class="main container">
        <div class="header"><strong>Header</strong></div>
        <div class="page">Page content</div>
    </div>

    <div class="footer">
        <div class="container"><strong>Footer</strong> <em>always at bottom ;) </em></div>
    </div>

</div></body>
</html>

请看jsfiddlepost

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接