中間內容高度不夠屏幕高度撐不開的頁面時候,頁面footer部分都能保持在網頁頁腳(最底部)的方法
1、首先上圖看顯示效果
2、奉上源碼
2.1、html部分
<body><header>頭部</header><main>主區域</main><footer>底部</footer>
</body>
2.2、css部分
<style>html, body {margin: 0;padding: 0;width: 100%;height: 100%;}body {min-height: 100vh;display: flex;flex-direction: column;}header {background: aquamarine;height: 40px;line-height: 40px;text-align: center;}footer {margin-top: auto;background: aquamarine;height: 50px;line-height: 50px;text-align: center;}main {align-self: center;/* 或者使用如下也可實現main區域居中顯示 *//* margin: 0 auto; */background: aqua;width: 80%;}</style>
3、全部代碼
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>flexbox布局</title><style>html, body {margin: 0;padding: 0;width: 100%;height: 100%;}body {min-height: 100vh;display: flex;flex-direction: column;}header {background: aquamarine;height: 40px;line-height: 40px;text-align: center;}footer {margin-top: auto;background: aquamarine;height: 50px;line-height: 50px;text-align: center;}main {align-self: center;background: aqua;width: 80%;}</style>
</head>
<body><header>頭部</header><main>主區域</main><footer>底部</footer>
</body>
</html>
?4、原理
1、首先,我們確保?
body
?元素至少會拉伸到屏幕的整個高度?min-height: 100vh
?。如果內容較短(某些移動瀏覽器除外),這不會觸發溢出,并且它將允許內容根據需要繼續拉伸高度。2、設置?
flex-direction: column
?在保留堆疊塊元素方面保持正常文檔流的行為(假設所有?body
?塊元素的直接子元素確實都是塊元素)。3、flexbox 的優勢在于利用該?
margin: auto
?行為。這個奇怪的伎倆將導致邊距填充它所設置的項目與其在相應方向上最近的兄弟姐妹之間的任何空間。設置?margin-top: auto
?會有效地將頁腳推到屏幕底部。?
5、缺陷
main區域不能自動高度填充?