八種方法實現CSS頁面底部固定

圖片描述
當咱們在寫頁面時常常會遇到頁面內容少的時候,footer會戳在頁面中間或什麼?反正就是不在最底部顯示,反正就是很難看,下面要講的佈局就是解決如何使元素粘住瀏覽器底部,html

方法一:footer高度固定+絕對定位

html前端

<div class="dui-container">
<header>Header</header>
<main>Content</main>
<footer>Footer</footer>
</div>

CSS瀏覽器

.dui-container{
position: relative;
min-height: 100%;
}
main {
padding-bottom: 100px;
}
header, footer{
line-height: 100px;
height: 100px;
}
footer{
width: 100%;
position: absolute;
bottom: 0
}

查看效果函數

方法二:在主體content上的下邊距增長一個負值等於底部高度

html佈局

<header>Header</header>
<main>Content</main>
<footer>Footer</footer>

CSSflex

html, body {
height: 100%;
}
main {
min-height: 100%;
padding-top: 100px;
padding-bottom: 100px;
margin-top: -100px;
margin-bottom: -100px;
}
header, footer{
line-height: 100px;
height: 100px;
}

查看效果ui

方法三:將頁腳的margin-top設爲負數

htmlflexbox

<header>Header</header>
<main>Content</main>
<footer>Footer</footer>

CSSspa

main {
min-height: 100%;
padding-top: 100px;
padding-bottom: 100px;
}
header, footer{
line-height: 100px;
height: 100px;
}
header{
margin-bottom: -100px;
}
footer{
margin-top: -100px;
}

查看效果3d

方法四: 經過設置flex,將footer的margin-top設置爲auto

html

<header>Header</header>
<main>Content</main>
<footer>Footer</footer>

CSS

body{
display: flex;
min-height: 100vh;
flex-direction: column;
}
header,footer{
line-height: 100px;
height: 100px;
}
footer{
margin-top: auto;
}

查看效果

方法五: 經過函數calc()計算內容的高度

html代碼

<header>Header</header>
<main>Content</main>
<footer>Footer</footer>

CSS代碼

main{
min-height: calc(100vh - 200px); /* 這個200px是header和footer的高度 */
}
header,footer{
height: 100px;
line-height: 100px;
}

查看效果

方法六: 經過設置flexbox,將主體main設置爲flex

html

<header>Header</header>
<main>Content</main>
<footer>Footer</footer>

CSS代碼

body{
display: flex;
min-height: 100vh;
flex-direction: column;
}
main{
flex: 1
}

查看效果

方法七: 使用grid佈局

Html代碼

<header>Header</header>
<main>Content</main>
<footer>Footer</footer>

CSS代碼

html {
height: 100%;
}
body {
min-height: 100%;
display: grid;
grid-template-rows: auto 1fr auto;
}
.footer {
grid-row-start: 3;
grid-row-end: 4;
}

查看效果

方法八: display-*

html

<header>Header</header>
<main>Content</main>
<footer>Footer</footer>

CSS

body {
  min-height: 100%;
  display: table;
  width: 100%;
}
main {
  display: table-row;
  height: 100%;
}

查看效果

做者: w3cbest前端開發
互動: 若有疑問 可進羣討論 本文原創,著做權歸做者全部。商業轉載請聯繫@w3cbest前端開發得到受權,非商業轉載請註明原連接及出處。
相關文章
相關標籤/搜索