footer置于页面最底部的方法

2017-07-12  本文已影响252人  arlene112

首先你需要判断你的footer是固定高度还是任意高度的,因为二者的方法有所却别,

现在先来说情形一,footer高度是固定的。有两种方法:

方法一:footer高度固定+绝对定位

css样式

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

html代码

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

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

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

方法二:footer高度固定+margin负值

css样式

html,body{height:100%;margin:0;padding:0;}

.container{min-height:100%;}

.header{background-color: #ffe4c4;}

.main{padding-bottom:100px;background-color: #bdb76b;}/*main的padding-bottom值要等于或大于footer的height值*/.footer{height:100px;margin-top:-100px;background-color: #ffc0cb;}/*margin-top(负值的)高度等于footer的height值*/

html代码

<div class="container">

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

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

</div>

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

如果footer高度任意,上面两种方法就失效了,要用下面的方法

方法三:footer高度任意+js

css样式

/*动态为footer添加类fixed-bottom*/.fixed-bottom {position:fixed;bottom:0;width:100%;}

<script type="text/javascript">

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

});

</script>

上一篇 下一篇

猜你喜欢

热点阅读