如何将页脚固定在页面底部?
要求:
- 如果页面内容不够长的时候,页脚块粘贴在视窗底部;
- 如果页面长度超出视窗时,页脚块会被内容向下推送。
方法一:
<div id="container">
<div id="header">Header Section</div>
<div id="page" class="clearfix">
页面容容部分
</div>
<div id="footer">Footer Section</div>
</div></pre>
- html,body高度设置为100%,并重置margin,padding为0;
- 其二div#container也需要设置min-height:100%,并处理好IE6下的min-height兼容问题;
- 其三也需要在div#page容器上设置一个padding-bottom或border-bottom-width值等于div#footer高度值(或略大于)。
- footer固定高度,绝对定位,bottom:0
方法二:
利用footer的margin-top负值来实现footer永远固定在页面的底部效果。
<div id="container">
<div id="page">Main Content</div>
</div>
<div id="footer">footer</div>
- html,body高度设置为100%,并重置margin,padding为0;
- 其二div#container也需要设置min-height:100%,并处理好IE6下的min-height兼容问题;
- 其三也需要在div#page容器上设置一个padding-bottom或border-bottom-width值等于div#footer高度值(或略大于)。
- div#footer与div#container容器是同级关系,如果你有新元素需要放置在与div#container容器同级,那你需要将此元素进行绝对定位,不然将会破坏div#container容器的min-height值;
- div#footer进行margin-top的负值设置,并且此值等于div#footer的高度值,而且也要和div#page容器的padding-bottom(或border-bottom-width)值相等。
方法三:
<div id="container">
<div id="page">Your Website content here.</div>
<div class="push"><!-- not have any content --></div>
</div>
<div id="footer">Footer Section</div>
- 同二类似html,body的设置100%,重置border,padding,margin
- container容器除了设置min-height及其兼容性外,设置margin-bottom取负值,值=footer.height+push.height+footer-padding+footer-border+push-padding+push-border;
-
div.push:在div.push内容为空,div必须放置在div#container容器中,而且是最底部,并且需要设置其高度值等于div#footer的值,最好加上clear:both来清除浮动。
div.push容器在此处所起的作用就是将footer往下推。 - div#footer容器:div#footer容器和方法二一样,不能放到div#container内部,而和div#container容器同级,如果需要设置元素和footer之间的间距,最好使用padding来代替margin值。
前面三种方法虽然没有使用jQuery等帮助,但我们都额外增加了HTML标签来实现效果。如果你省略了这些HTML标签,再要实现效果就比较困难了,那么此时使用jQuery或javaScript方法来帮助实现是一种很好的办法,下面我们就一起来看第四种方法,通过jQuery来实现页脚永远固定在页面底部的效果。
<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>
<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";
//如果页面内容高度小于屏幕高度,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>
网友评论