我有以下页面(deadlink: http://www.workingstorage.com/Sample.htm),有一个脚注,我不能坐在页面的底部。
我想让页脚
当页面较短且屏幕未被填充时,坚持在窗口底部 当有超过一个屏幕的内容时,保持在文档末尾,并像往常一样向下移动(而不是重叠内容)。
CSS是继承的,让我困惑。我似乎不能正确地改变它,把一个最小高度的内容或使页脚到底部。
我有以下页面(deadlink: http://www.workingstorage.com/Sample.htm),有一个脚注,我不能坐在页面的底部。
我想让页脚
当页面较短且屏幕未被填充时,坚持在窗口底部 当有超过一个屏幕的内容时,保持在文档末尾,并像往常一样向下移动(而不是重叠内容)。
CSS是继承的,让我困惑。我似乎不能正确地改变它,把一个最小高度的内容或使页脚到底部。
当前回答
只需将html、正文和除页脚之外的其他行设置为100%。 如
<body>
<header></header>
<content></content>
<footer></footer>
the CSS becomes
html, body, header, content{
height:100%;
}
其他回答
与其他解决方案相比,不需要添加额外的容器。因此,这个解决方案更优雅一些。在代码示例下面,我将解释为什么这样工作。
<!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。这确保主体实际上比它的内容更大。
这就是所谓的粘性页脚。在谷歌上搜索它会出现很多结果。我成功地使用过CSS Sticky Footer。但还有更多。
* { margin: 0; } html, body { height: 100%; } .wrapper { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -4em; } .footer, .push { height: 4em; } <html> <head> <link rel="stylesheet" href="layout.css" ... /> </head> <body> <div class="wrapper"> <p>Your website content here.</p> <div class="push"></div> </div> <div class="footer"> <p>Copyright (c) 2008</p> </div> </body> </html>
此代码的源代码
使用Flexbox保持页脚在底部
< div风格= "最小高度:100 vh;显示:flex;flex-direction:列; justify-content:之间的空间;" > < div > < !——包装(不带页脚)——> <标题> 我是头。 头> < / 文章< > 我是一篇文章! < / >的文章 < / div > < !——结束:包装器(没有页脚)——> <页脚> 我是一个脚注。 > < /页脚 < / div >
Note
确保你将所有内容包装在<div>或任何其他块级元素中,使用以下CSS样式:显示:flex;flex-direction:列;justify-content:之间的空间;. 确保在<div>或任何其他块级元素中包装了除页脚元素以外的所有内容。 确保您使用<footer>或任何其他块级元素来包装页脚。
代码的解释
Min-height: 100vh确保主体元素至少伸展到屏幕的全部高度 Flex-direction:列在保留堆叠块元素方面保持正常文档流的行为(假设主体的直接子元素确实都是块元素)。 对齐-内容:空格将页脚推到屏幕底部。
检查如何做同样的(保持页脚在底部)通过使用引导5 -链接
一个简单的方法是让页面主体100%,最小高度也为100%。如果你的页脚的高度没有改变,这工作得很好。
给页脚一个负的margin-top:
footer {
clear: both;
position: relative;
height: 200px;
margin-top: -200px;
}
我的jQuery方法,这一个把页脚放在页面的底部,如果页面内容小于窗口高度,或者只是把页脚放在内容之后,否则:
此外,在其他代码之前将代码保存在自己的附件中,将减少重新定位页脚所需的时间。
(function() {
$('.footer').css('position', $(document).height() > $(window).height() ? "inherit" : "fixed");
})();