CSS頁面底部固定的6種方法,你確定不想學?

CSS頁面底部固定的6種方法,你確定不想學?

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

方法一: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>

CSS

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;
}

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

html

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

CSS

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;
}

方法四: 通過設置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
}

自己是一個五年的前端工程師

這裏推薦一下我的前端學習交流羣:731771211,裏面都是學習前端的從最基礎的HTML+CSS+JS【炫酷特效,遊戲,插件封裝,設計模式】到移動端HTML5的項目實戰的學習資料都有整理,送給每一位前端小夥伴。不定時更新技術,與企業需求同步。好友都在裏面交流,每天都會有大牛定時講解前端技術!

點擊:加入

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章