2011-04-21 19 views

回答

15

它們在功能上非常相似。第一個強制一個div到頁面的整個高度,然後給它一個頁腳大小的負邊距。

html, body { 
    height: 100%; /*set 100% height*/ 
} 
.wrapper { 
    min-height: 100%; /*content 100% height of page */ 
    height: auto !important; 
    height: 100%; 
    margin: 0 auto -142px; /* negative value causes wrappers height to become (height of page) minus 142px, just enough room for our footer */ 
} 
.footer, .push { 
    height: 142px; /*Footer is the footer, push pushes the page content out of the footers way*/ 
} 

這樣做是爲了確保包裝div內的所有內容都是頁面高度的100%減去頁腳的高度。因此,只要頁腳的尺寸與負頁邊的尺寸相同,它就會粘在留下的空白處並出現在元素的底部。

第二個也強制內容爲頁面高度的100%。

html, body {height: 100%;} /*set 100% height*/ 

#wrap {min-height: 100%;} /* make content 100% height of screen */ 

然後它會在主內容的底部創建一個與頁腳大小相同的空格。

#main {overflow:auto; 
padding-bottom: 150px;} /* wrapper still 100% height of screen but its content is forced to end 150px before it finishes (150px above bottom of screen) */ 

然後,使用位置的相對和負極上邊距迫使頁腳顯示150像素以上的正常位置(在該空間中,它只是製造)。

#footer {position: relative; 
margin-top: -150px; /* Make footer appear 150px above its normal position (in the space made by the padding in #main */ 
height: 150px; 
clear:both;} 

注:這僅適用,只要你的頁面內容分別保持.wrapper內#main內#wrap,和你的頁腳是這些容器的外面。

如果你不明白任何部分給我留下評論,我會盡力回答。

編輯:響應於user360122

HTML標記爲第一:

<html> 
<body> 
<div class="wrapper"> 
<!--Page content goes here--> 
<div class="push"> 
<!--Leave this empty, it ensures no overflow from your content into your footer--> 
</div> 
</div> 
<div class="footer"> 
<!--Footer content goes here--> 
</div> 
<body> 
</html> 

HTML標記爲第二:

<html> 
<body> 
<div id="wrap"> 
<div id="main"> 
<!--Page content goes here--> 
</div> 
</div> 
<div id="footer"> 
<!--Footer content goes here--> 
</div> 
</body> 
</html> 

請記住,包括樣式表,並聲明DOCTYPE .etc (這些不是完整的HTML頁面)。

+0

好答案喬治 – David 2011-04-21 16:13:56

+0

嗨喬治,你有它的HTML標記嗎?非常感謝。 – HorseKing 2011-06-24 14:29:31

+0

用html標記更新 – 2011-06-24 16:03:06

1

有引導文件,這似乎是很簡單的一個例子:http://getbootstrap.com/examples/sticky-footer/

無包裝或按需要。

html { 
    position: relative; 
    min-height: 100%; 
} 
body { 
    /* Margin bottom by footer height */ 
    margin-bottom: 60px; 
} 
#footer { 
    position: absolute; 
    bottom: 0; 
    width: 100%; 
    /* Set the fixed height of the footer here */ 
    height: 60px; 
    background-color: #f5f5f5; 
} 
+0

在IE7中不起作用。認爲使用push-div的人最好使用跨瀏覽器,而不使用js。 – sasha 2014-11-15 12:12:27