在以下所有示例中,我仅使用了三个div:标题、内容和页脚来包含基本的HTML模板。所有选项都已被压缩,但在更高级的网站上也应该可以正常工作。
为body和footer设置相同的background-color。
body {
margin: 0px;
font-family: Arial;
line-height: 20px;
background-color: red;
}
#header {
height: 20px;
background: #222;
color: white;
}
#content {
background: gray;
height: 200px;
}
#footer {
height: 20px;
background: red; /*Same as body, you could also use transparent */
color: white;
}
<div id="header">
Header
</div>
<div id="content">
Content
</div>
<div id="footer">
Footer
</div>
使用一个固定在浏览器窗口底部的粘性页脚。 (我不建议使用这个选项,因为许多用户不喜欢粘性页脚。但是您可以使用粘性标题)
body {
margin: 0px;
font-family: Arial;
line-height: 20px;
}
#header {
height: 20px;
background: #222;
color: white;
}
#content {
height: 2000px;
}
#footer {
position: fixed;
width: 100%;
bottom: 0;
left: 0;
height: 20px;
background: #222;
color: white;
}
<div id="header">
Header
</div>
<div id="content">
Content
</div>
<div id="footer">
Footer
</div>
为内容部分设置一个最小高度,该高度等于浏览器窗口高度减去页眉和页脚的高度。(这是我个人最喜欢的方法,因为它可以跨浏览器工作,并且在所有屏幕上都响应)
body {
margin: 0px;
font-family: Arial;
line-height: 20px;
}
#header {
height: 20px;
background: #222;
color: white;
}
#content {
min-height: calc(100vh - 40px);
}
#footer {
height: 20px;
background: #222;
color: white;
}
<div id="header">
Header
</div>
<div id="content">
Content
</div>
<div id="footer">
Footer
</div>
HTML:
<body>
<section>
This is content of the page
</section>
<footer>
Text of footer
</footer>
</body>
CSS:
section {
min-height: 100vh; /* minus the height of the footer */
}
jsfiddle链接:https://jsfiddle.net/x55xh3v7/
更加“优化”的解决方案是粘性页脚技术,它可以防止页脚不必要地流出页面。
也可以像这样完成
#main{
border:solid;
height:100vh;
}
#footer{
border:solid;
}
<div id="main">
Everything here
</div>
<div id="footer">
footer
</div>
我建议使用JavaScript来解决这个问题,可以像这样:
if($(window).height() > $("body").height()){
$("footer").css("position", "fixed");
} else {
$("footer").css("position", "static");
}