在內容超出屏幕時,footer只有在滾動條拉直底部時纔出現。當撐不滿屏幕時,footer直接固定在底部。javascript
主體區域 min-height:100%, 剛好把 footer 擠出一屏外,footer 自己使用負的 margin-top 往上提與 height 相同的距離,這時只需在主體區內部元素上添加 padding-bottom 把 footer 蓋住的區域排開便可。css
html: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>
css:java
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;
}
js:jquery
$(function(){ $("#add").click(function(){ $(".main").append('<p>test test test</p>'); }); })
其實使用 css3 calc 的話,能夠很簡單地將vh和絕對單位混算,DOM結構就無需如此彆扭了,直接 min-height: calc(100vh - 60px); 就行了css3
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;
}