如何将页脚固定在页面底部

html-css014

如何将页脚固定在页面底部,第1张

让我们实现了页脚永远固定在页面底部的效果,但我们都额外增加了HTML标签来实现效果。如果你省略

了这些HTML标签,再要实现效果就比较困难了,那么此时使用jQuery或javaScript方法来帮助实现是一种很好的办法,下面我们就一起来看,通过jQuery来实现页脚永远固定在页面底部的效果。

HTML Markup

<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>

这里我们没有增加没用的HTML标签,此时你也可以随时在body中增加内容,只要确保div#footer是在body最后面。

<div id="footer">Footer Section</div>

CSS Code

*{margin: 0padding: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

}

这个方法不像前面三种方法靠CSS来实现效果,这里只需要按正常的样式需求写样式,不过有一点需要特别注意在html,body中不可以设置高度height为100%,否则此方法无法正常运行,如果你在div#footer中设置了一个高度并把宽度设置为100%将更是万无一失了。

jQuery Code

<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()

//定义position Footer 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>

使用上面的jQuery代码,可以轻松的帮我们实现页脚永远固定在页面底部,使用这种方法有几个地方需要注意

1. 确保正常引入了jQuery版本库,并正常调入了上面那段jQuery代码;

2. 确保<div id=”footer”>是在body中最后;

3. 确保在html,body中没有设置高度为100%。

优点:

结构简单,无需外加无用标签,兼容所有浏览器,不用另外写特别样式。页脚可以不固定高度。

缺点:

在不支持js的浏览器中无法正常显示,另外每次改变浏览器大小会闪动一下。

最快的方式是将底部的设置定位,也是最常见方式。

例子:

<style type="text/css">

.main{

padding-bottom: x px/*x 和底部的高度相同*/

}

.foter{

position: fixed

height: xpx/*x 是你底部的高度*/

width: 100%

left: 0px

bottom: 0px

}

</style>

<div class="header">头部</div>

<div class="main">内容</div>

<div class="footer">底部</div>

希望能给你帮助。

给页脚内容标签设置css固定定位:position: fixedbottom: 0

当然,前提是页脚内容标签的父标签也要设置相对定位:position: relative 。页脚的父标签一般是body,或者自己另外设置。当父标签是body时,可以不用写position: relative,网页会默认选择body作为父标签的