我发现了 2 种不同的 CSS 粘性页脚实现:
Ryan Fait 粘性页脚 - http://ryanfait.com/sticky-footer/
Steve Hatcher 粘页脚 - http://www.cssstickyfooter.com/
有人可以解释他们每个人的工作方式之间的区别吗?
如果还有其他已知的实现,您能否发表评论或编辑这个问题?
我发现了 2 种不同的 CSS 粘性页脚实现:
Ryan Fait 粘性页脚 - http://ryanfait.com/sticky-footer/
Steve Hatcher 粘页脚 - http://www.cssstickyfooter.com/
有人可以解释他们每个人的工作方式之间的区别吗?
如果还有其他已知的实现,您能否发表评论或编辑这个问题?
它们在功能方面非常相似。第一个强制一个 div 到页面的全高,然后给它一个负边距页脚的大小。
html, body {
height: 100%; /*set 100% height*/
}
.wrapper {
min-height: 100%; /*content 100% height of page */
height: auto !important;
height: 100%;
margin: 0 auto -142px; /* negative value causes wrappers height to become (height of page) minus 142px, just enough room for our footer */
}
.footer, .push {
height: 142px; /*Footer is the footer, push pushes the page content out of the footers way*/
}
这样做是为了确保包装 div 中的所有内容都是页面高度减去页脚高度的 100%。这样只要页脚的大小与负边距相同,它就会粘在左边的间隙中并出现在元素的底部。
第二个还强制内容为页面高度的 100%。
html, body {height: 100%;} /*set 100% height*/
#wrap {min-height: 100%;} /* make content 100% height of screen */
然后它在主要内容的底部创建一个与页脚大小相同的空间。
#main {overflow:auto;
padding-bottom: 150px;} /* wrapper still 100% height of screen but its content is forced to end 150px before it finishes (150px above bottom of screen) */
然后使用相对位置和负上边距强制页脚出现在其正常位置上方 150 像素(在它刚刚创建的空间中)。
#footer {position: relative;
margin-top: -150px; /* Make footer appear 150px above its normal position (in the space made by the padding in #main */
height: 150px;
clear:both;}
注意:这仅适用于您的页面内容分别保存在 .wrapper 和 #main 内的 #wrap 内,并且您的页脚位于这些容器之外。
如果您不理解其中的任何部分,请给我留言,我会尽力回答。
编辑:响应 user360122
首先是 HTML 标记:
<html>
<body>
<div class="wrapper">
<!--Page content goes here-->
<div class="push">
<!--Leave this empty, it ensures no overflow from your content into your footer-->
</div>
</div>
<div class="footer">
<!--Footer content goes here-->
</div>
<body>
</html>
第二个 HTML 标记:
<html>
<body>
<div id="wrap">
<div id="main">
<!--Page content goes here-->
</div>
</div>
<div id="footer">
<!--Footer content goes here-->
</div>
</body>
</html>
请记住包含样式表并声明 doctype .etc(这些不是完整的 html 页面)。
引导文档中有一个似乎非常简单的示例:http: //getbootstrap.com/examples/sticky-footer/
无需包装或推送。
html {
position: relative;
min-height: 100%;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
}
#footer {
position: absolute;
bottom: 0;
width: 100%;
/* Set the fixed height of the footer here */
height: 60px;
background-color: #f5f5f5;
}