HTML:
<div id="header">Header Section</div>
<div id="page" class="clearfix">
<div id="left">Left sidebar</div>
<div id="content">Main Content</div>
<div id="right">Right Content</div>
</div>
<div id="footer">Footer Section</div>
CSS:
*{margin: 0;padding:0;}
.clearfix:before,
.clearfix:after {
content:"";
display:table;
}
.clearfix:after {
clear:both;
}
.clearfix {
zoom:1; /* IE <8 */
}
#footer{
height: 60px;
background: #fc6;
width: 100%;
}
/*==========其他div==========*/
#header {
padding: 10px;
background: lime;
}
#left {
width: 18%;
float: left;
margin-right: 2%;
background: orange;
}
#content{
width: 60%;
float: left;
margin-right: 2%;
background: green;
}
#right {
width: 18%;
float: left;
background: yellow;
}
特別注意在html,body中不可以設置高度height爲100%,否則此方法無法正常運行,如果你在div#footer中設置了一個高度並把寬度設置爲100%將更是萬無一失了。
JQuery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
// Window load event used just in case window height is dependant upon images
$(window).bind("load", function() {
var footerHeight = 0,
footerTop = 0,
$footer = $("#footer");
positionFooter();
//定義positionFooter function
function positionFooter() {
//取到div#footer高度
footerHeight = $footer.height();
//div#footer離屏幕頂部的距離
footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
/* DEBUGGING STUFF
console.log("Document height: ", $(document.body).height());
console.log("Window height: ", $(window).height());
console.log("Window scroll: ", $(window).scrollTop());
console.log("Footer height: ", footerHeight);
console.log("Footer top: ", footerTop);
console.log("-----------")
*/
//如果頁面內容高度小於屏幕高度,div#footer將絕對定位到屏幕底部,否則div#footer保留它的正常靜態定位
if ( ($(document.body).height()+footerHeight) < $(window).height()) {
$footer.css({
position: "absolute"
}).stop().animate({
top: footerTop
});
} else {
$footer.css({
position: "static"
});
}
}
$(window).scroll(positionFooter).resize(positionFooter);
});
</script>