方法一:footer 高度固定+绝对定位
<body>
<header>header</header>
<main>content</main>
<footer>footer</footer>
</body>
html{height:100%;}
body{min-height:100%;margin:0;padding:0;position:relative;}
header{background-color: #ffe4c4;}
main{padding-bottom:100px;background-color: #bdb76b;}/* main的padding-bottom值要等于或大于footer的height值 */
footer{position:absolute;bottom:0;width:100%;height:100px;background-color: #ffc0cb;}
首先,设置 body 的高度至少充满整个屏幕,并且 body 作为 footer 绝对定位的参考节点;
其次,设置 main(footer 前一个兄弟元素)的 padding-bottom 值大于等于 footer 的 height 值,以保证 main 的内容能够全部显示出来而不被 footer 遮盖;
最后,设置 footer 绝对定位,并设置 height 为固定高度值。
方法二:footer 高度任意+js
<body>
<header>header</header>
<main>main content</main>
<footer>footer</footer>
</body>
html,body{margin:0;padding: 0;}
header{background-color: #ffe4c4;}
main{background-color: #bdb76b;}
footer{background-color: #ffc0cb;}
/* 动态为footer添加类fixed-bottom */
.fixed-bottom {position: fixed;bottom: 0;width:100%;}
$(function(){
function footerPosition(){
$("footer").removeClass("fixed-bottom");
var contentHeight = document.body.scrollHeight,//网页正文全文高度
winHeight = window.innerHeight;//可视窗口高度,不包括浏览器顶部工具栏
if(!(contentHeight > winHeight)){
//当网页正文高度小于可视窗口高度时,为footer添加类fixed-bottom
$("footer").addClass("fixed-bottom");
} else {
$("footer").removeClass("fixed-bottom");
}
}
footerPosition();
$(window).resize(footerPosition);
});