CSS五種方式實現Footer置底
頁腳置底(Sticky footer)就是讓網頁的footer部分始終在瀏覽器窗口的底部。
當網頁內容足夠長以至超出瀏覽器可視高度時,頁腳會隨著內容被推到網頁底部;
但如果網頁內容不夠長,置底的頁腳就會保持在瀏覽器窗口底部。
方法一:將內容部分的 margin-bottom 設為負數
<div class="wrapper">
<!-- content -->
<div class="push"></div>
</div>
<div class="footer">footer</div>
html, body {
margin: 0;
padding: 0;
height: 100%;
}
.wrapper {
min-height: 100%;
margin-bottom: -50px; /* 等于footer的高度 */
}
.footer, .push {
height: 50px;
}
-
這個方法需要容器里有額外的占位元素( div.push )。
-
div.wrapper 的 margin-bottom 需要和 div.footer 的 -height 值一樣,注意是負 height 。
方法二:將頁腳的 margin-top 設為負數
-
給內容外增加父元素,并讓內容部分的 padding-bottom 與頁腳的 height 相等。
<div class="content">
<div class="content-inside">
<!-- content -->
</div>
</div>
<div class="footer">footer</div>
html, body {
margin: 0;
padding: 0;
height: 100%;
}
.content {
min-height: 100%;
}
.content-inside {
padding: 20px;
padding-bottom: 50px;
}
.footer {
height: 50px;
margin-top: -50px;
}
方法三:使用 calc() 設置內容高度
<div class="content">
<!-- content -->
</div>
<div class="footer">footer</div>
.content {
min-height: calc(100vh - 70px);
}
.footer {
height: 50px;
}
-
這里假設 div.content 和 div.footer 之間有20px的間距,所以70px=50px+20px
方法四:使用flexbox彈性盒布局
以上三種方法的footer高度都是固定的,如果footer的內容太多則可能會破壞布局。
<div class="content">
<!-- content -->
</div>
<div class="footer">footer</div>
html {
height: 100%;
}
body {
min-height: 100%;
display: flex;
flex-direction: column;
}
.content {
flex: 1;
}
方法五:使用Grid網格布局
<div class="content">
<!-- content -->
</div>
<div class="footer">footer</div>
html {
height: 100%;
}
body {
min-height: 100%;
display: grid;
grid-template-rows: 1fr auto;
}
.footer {
grid-row-start: 2;
grid-row-end: 3;
}
來自:https://segmentfault.com/a/1190000008516654
本文由用戶 GlaIFG 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!