本文介紹了CSS Sticky Footer實現代碼,分享給大家,具體如下:
上圖所顯示的效果就是sticky Footer,當頁面主題內容不夠長時,footer定位在窗口的底部,當頁面主題內容超出窗口后,footer顯示在頁面的最底部
以下給出幾種實現方案:
1. FlexBox布局
HTML結構如下:
<body> <div class="header">Sticky Footer</div> <div class="content"> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> </div> <div class="footer"> <p>This is footer</p> </div></body>
主要CSS如下:
body{ display: flex; flex-flow: column; min-height: 100vh;}.content{ flex: 1;}
FlexBox實現就是這么簡單,實現效果也貼上來
貼圖的效果好像不太好,但是效果是實現了的哦?。。。?/p>
2. 經典套路:padding-bottom + margin-top
HTML結構如下:
<body> <div class="wrapper clearfix"> <div class="title">Sticky Footer</div> <div class="content"> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> </div> </div> <div class="footer"> <p>This is footer</p> </div></body>
主要CSS如下:
.wrapper{ min-height: 100vh;}.content{ padding-bottom: 50px;}.footer{ height: 50px; margin-top: -50px;}
實現效果(感覺需要裝個錄屏軟件了):
使用此方案時要注意以下幾點:
1. wrapper的最小高度要等于窗口高度
2. content的padding-bottom、footer的margin-top和height這三個屬性值的絕對值需保持一致(因為margin-top為負值,所以說絕對值);保持一致的原因是更好的實現sticky footer,雖然height什么的偏小也能實現sticky footer效果,但是給最底部留下了空隙。
3. 這種方案的兼容性不錯,各大主流瀏覽器均可,emmmmm,還不錯
4. 當主體使用懸浮布局的時候,那么就需要考慮一個兼容性問題,這里使用的重點是為了Google chrome
上述第四條兼容性解決方案:
給.wrapper加上著名的clearfix hack:
.clearfix{ display: inline-block}.clearfix:after{ display: block content: "." height: 0 line-height: 0 clear: both visibility: hidden}
3. 固定高度的解決方案
HTML結構如下:
<body> <div class="wrapper"> <div class="header">Sticky Footer</div> <div class="content"> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> <p>測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試</p> </div> </div> <div class="footer"> <p>This is footer</p> </div></body>
主要CSS樣式如下:
.wrapper{ min-height: calc(100vh - 50px); box-sizing: border-box;}
注:50px為footer的高度,calc()運算符前后都需要保留一個空格。
結果我就不貼了,大家自行腦補,跟上面的都差不多。。。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答