文章目錄
- 一、粘連布局
- 二、簡單實作
- 三、實戰-簡化DOM結構
- 注意要點
一、粘連布局
特點:
-
有一塊內容
<main>,當<main>的高康足夠長的時候,緊跟在<main>后面的元素<footer>會跟在<main>元素的后面滾動, -
當
<main>元素比較短的時候(比如小于螢屏的高度),我們期望這個<footer>元素能夠“粘連”在螢屏的底部
如圖:圖片來源https://blog.csdn.net/VhWfR2u02Q/article/details/84076421


二、簡單實作
DOM結構:
<body>
<div class="wrap">
<div class="main">
<div class="content">content</div>
</div>
</div>
<div class="footer">footer</div>
</body>
樣式:
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;/*高度一層層繼承下來*/
}
.wrap{
min-height: 100%;
text-align: center;
}
.wrap .main{
padding-bottom: 100px;
}
.footer{
height: 100px;
line-height: 100px;
background: #3af;
text-align: center;
margin-top: -100px;
}
.content{
height: 200px;
background: pink;
}
</style>
-
footer必須是一個獨立的結構,與wrap沒有任何嵌套關系
-
wrap區域的高度通過設定min-height,變為視口高度
-
footer要使用margin為負來確定自己的位置
-
在main區域需要設定 padding-bottom,這也是為了防止負 margin 導致 footer 覆寫任何實際內容,
看看效果:
內容不多時,footer固定在底部

內容多的時候,footer跟隨在后面滾動:

三、實戰-簡化DOM結構
上面是資訊串列,下面是確認按鈕,之前的按鈕是用的絕對定位,我需要把它改為粘連布局的,串列不長時,按鈕固定在底部,串列資訊比較多的時候,按鈕跟隨在后面滾動,
DOM節點是這樣的:
<div class="main">
<div class="list-info">info</div>
<div class="list-info">info</div>
<div class="list-info">info</div>
<div class="list-info">info</div>
</div>
<div class="button">確認</div>
那我要用粘連布局,還得在main的外面需要包一層wrap,這顯得有點冗余,我不想多嵌套這一層,
所以一陣探索后,得出一個方案,
demo:
DOM結構如下:
<div class="main">
<div class="content">content</div>
</div>
<div class="footer">footer</div>
樣式如下:
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;/*高度一層層繼承下來*/
}
.main{
box-sizing: border-box;
min-height: 100%;
padding-bottom: 100px;
}
.footer{
height: 100px;
line-height: 100px;
background: #3af;
text-align: center;
margin-top: -100px;
}
.content{
text-align:center;
height: 200px;
background: pink;
}
</style>
注意要點
-
main需要加上:
box-sizing: border-box;
計算高度的時候會把padding計算進去(涉及盒模型相關知識)
設定box-sizing: border-box;,怪異盒模型,height = contnet.height+padding+border
這里height100%=667px= contnet.height+padding+border,剛好占滿螢屏
設定box-sizing: content-box;,標準盒模型,height = contnet.height
這里height100%=667px= contnet.height,已經100%占滿螢屏,
再加上padding-bottom: 100px = 767,就超出螢屏了,會把footer擠到螢屏外面去了,無法正常顯示, -
當時遇到個問題,如果body上我是設定的
min-height: 100%;,那么我main上設定的min-height: 100%;不會生效原因:
父元素設定了 min-height但沒有設定 height時候,子元素的height 和 min-height 不會生效,子元素的 height 或是 min-height 是否生效,基于父元素是否設定了固定高度或者是一個有效百分比高度,
本文鏈接https://blog.csdn.net/qq_39903567/article/details/115556127
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/274752.html
標籤:其他
