我有以下页面(deadlink: http://www.workingstorage.com/Sample.htm),有一个脚注,我不能坐在页面的底部。
我想让页脚
当页面较短且屏幕未被填充时,坚持在窗口底部 当有超过一个屏幕的内容时,保持在文档末尾,并像往常一样向下移动(而不是重叠内容)。
CSS是继承的,让我困惑。我似乎不能正确地改变它,把一个最小高度的内容或使页脚到底部。
我有以下页面(deadlink: http://www.workingstorage.com/Sample.htm),有一个脚注,我不能坐在页面的底部。
我想让页脚
当页面较短且屏幕未被填充时,坚持在窗口底部 当有超过一个屏幕的内容时,保持在文档末尾,并像往常一样向下移动(而不是重叠内容)。
CSS是继承的,让我困惑。我似乎不能正确地改变它,把一个最小高度的内容或使页脚到底部。
当前回答
一个简单的方法是让页面主体100%,最小高度也为100%。如果你的页脚的高度没有改变,这工作得很好。
给页脚一个负的margin-top:
footer {
clear: both;
position: relative;
height: 200px;
margin-top: -200px;
}
其他回答
虽然我找到了许多类似的答案,但我能找到的唯一解决方案是,页脚总是在底部,不显示在现有数据之上:
footer {
position: relative;
clear: both;
}
我使用的一个简单的解决方案,从IE8+工作
在html上给min-height:100%,这样如果内容较少,那么页面仍然采用完整的视图高度,页脚贴在页面底部。当内容增加时,页脚随着内容向下移动,并保持贴在底部。
JS小提琴工作演示:http://jsfiddle.net/3L3h64qo/2/
Css
html{
position:relative;
min-height: 100%;
}
/*Normalize html and body elements,this style is just good to have*/
html,body{
margin:0;
padding:0;
}
.pageContentWrapper{
margin-bottom:100px;/* Height of footer*/
}
.footer{
position: absolute;
bottom: 0;
left: 0;
right: 0;
height:100px;
background:#ccc;
}
Html
<html>
<body>
<div class="pageContentWrapper">
<!-- All the page content goes here-->
</div>
<div class="footer">
</div>
</body>
</html>
然而,另一个非常简单的解决方案是:
html, body {
height: 100%;
width: 100%;
margin: 0;
display: table;
}
footer {
background-color: grey;
display: table-row;
height: 0;
}
js小提琴
诀窍是使用display:table表示整个文档,使用display:table-row(高度为0)表示页脚。
由于页脚是唯一显示为表行的子主体,因此它呈现在页面底部。
只需要自定义页脚部分
.footer
{
position: fixed;
bottom: 0;
width: 100%;
padding: 1rem;
text-align: center;
}
<div class="footer">
Footer is always bootom
</div>
与其他解决方案相比,不需要添加额外的容器。因此,这个解决方案更优雅一些。在代码示例下面,我将解释为什么这样工作。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
html
{
height:100%;
}
body
{
min-height:100%;
padding:0; /*not needed, but otherwise header and footer tags have padding and margin*/
margin:0; /*see above comment*/
}
body
{
position:relative;
padding-bottom:60px; /* Same height as the footer. */
}
footer
{
position:absolute;
bottom:0px;
height: 60px;
background-color: red;
}
</style>
</head>
<body>
<header>header</header>
<footer>footer</footer>
</body>
</html>
所以我们要做的第一件事,就是让最大的容器(html) 100%html页面和页面本身一样大。接下来我们设置body height,它可以大于html标签的100%,但它至少应该一样大,因此我们使用min-height 100%。
我们也让物体是相对的。相对意味着您可以相对地从原始位置移动块元素。但我们在这里不用。因为相对还有第二个用途。任何绝对元素要么是根元素(html)的绝对元素,要么是第一个相对父元素/祖父元素的绝对元素。这就是我们想要的,我们想要footer是绝对的,相对于主体,也就是底部。
最后一步是将footer设置为absolute和bottom:0,这将把它移动到第一个相对的父/祖父类(当然是body)的底部。
现在我们还有一个问题要解决,当我们填满整个页面时,内容会放在页脚下面。为什么?好吧,因为页脚不再在“html流”,因为它是绝对的。那么我们如何解决这个问题呢?我们将在body中添加padding-bottom。这确保主体实际上比它的内容更大。