将 footer 固定在浏览器底部

在内容超出屏幕时,footer只有在滚动条拉直底部时才出现。当撑不满屏幕时,footer直接固定在底部。

主体区域 min-height:100%, 恰好把 footer 挤出一屏外,footer 本身使用负的 margin-top 往上提与 height 相同的距离,这时只需在主体区内部元素上添加 padding-bottom 把 footer 盖住的区域排开即可。

html:

<!DOCTYPE HTML>
<html lang="en">
    <head>
    <script id="jquery_182" type="text/javascript" class="library" src="/js/sandbox/jquery/jquery-1.8.2.min.js"></script>
    </head>
    <body>
        <div class="wrapper">
            <div class="header">header</div>
            <div class="main">
                  <button id="add">add</button>
                    <p>test test test</p>
            </div>
        </div>
      <div class="footer">footer</div>
    </body>
</html>
View Code

 

css:

html{
    height:100%;
}
body{
    height: 100%;
    margin: 0;
    background: white;
}
.wrapper{
    min-height:100%;
    height:auto;
}
.main{
    padding-bottom: 60px;
}
.footer,.header{
    color: white;
    text-align:center;
    height: 60px;
    line-height:60px;
    background:#376AAE;
}
.footer{
    margin-top:-60px;
}

p{
    margin:0;
    padding:10px;
    background:white;
}
View Code

 

js:

$(function(){
    $("#add").click(function(){
      $(".main").append('<p>test test test</p>');
    });
})
View Code

 

其实使用 css3 calc 的话,可以很简单地将vh和绝对单位混算,DOM结构就无需如此别扭了,直接 min-height: calc(100vh - 60px); 就好了

body{
    margin: 0;
    background: white;
}
.main{
    min-height:calc(100vh - 120px);
}
.footer,.header{
    color: white;
    text-align:center;
    height: 60px;
    line-height:60px;
    background:#376AAE;
}

p{
    margin:0;
    padding:10px;
    background:white;
}
View Code

 

posted @ 2017-09-11 20:16  前端渣小白  Views(655)  Comments(0Edit  收藏  举报