想滾就滾、不想滾就不滾的footer
今天紀錄的是前端開發的 一個小tip,沒有太高的技術含量,但是開發過程中時常遇見。
Requirement:
實現兩種footer
1、一直固定在底部,無論頁面長短,始終能看見的footer,稱其為不想滾的footer。
2、同樣固定在底部,在頁面較長的時候,需要滾動到頁面結尾才能看見的footer,稱其為想滾的footer。
Implementation:
- 不想滾的footer
html:
<div class="container">
<div class="main-content">
</div>
<footer>
</footer>
</div>
css:
.container {position: relative;}
.main-content {
height: 1200px;
padding-bottom: 70px;
//一定要給footer留位置,否則會出現內容被footer遮蓋的現象
}
footer {
height: 70px;
background-color: #4d4d4d;
left: 0;
bottom: 0;
width: 100%;
position: fixed; //這個是關鍵哦!
}
效果:
Paste_Image.png
1、此時主要內容.main-content的長度為1200px,footer還依然顯示在界面上,效果圖右側的滾動條為證。
2、原理即是footer相對其父元素.container的位置為固定的,通過設置bottom和left固定。
-
想滾的footer
html:
<div class="main-container">
<div class="main-content">
</div>
<footer>
</footer>
</div>
css:
html, body { height: 100%; //關鍵1}
.main-container { min-height: 100%; //關鍵2 position: relative;}
.main-content { height: 1200px; padding-bottom: 70px; //關鍵3}
footer {
height: 70px;
background-color: #4d4d4d;
width: 100%;
position: absolute; //關鍵4
bottom: 0;
}
效果:
Paste_Image.png
關鍵1:一定要設置html和body的高度為100%,保證內容不足的時候撐開頁面,保證footer在底部。
關鍵2:不要設置根div的class為container。因為container包含了很多html原生的樣式,需要自己做調整。并且一定要設置根div的最小高度為100%,原因和關鍵1一樣。
關鍵3:一定要設置主內容的padding-bottom為footer的高度,避免在頁面最底部出現footer遮蓋主內容的現象。
關鍵4:設置footer相對于父div為絕對位置。
看到自己的文章被推薦到首頁還是有點小興奮的。我會繼續努力的!
(??`ω′?)