在網頁設計中,Sticky footers設計是最古老和最多見的效果之一,大多數人都曾經經歷過。它能夠歸納以下:若是頁面內容不夠長的時候,頁腳塊粘貼在視窗底部;若是內容足夠長時,頁腳塊會被內容向下推送,咱們看到的效果就以下面兩張圖這樣。這種效果基本是無處不在的,很受歡迎。html
那麼面對這樣的問題有什麼解決方法呢?首先咱們先構建簡單的代碼app
<body>
<div class="content"></div> <div class="footer"></div>
</body>
其中content爲咱們的內容區。下面開始介紹解決方法。佈局
1、爲內容區域添加最小的高度flex
這種方法重要用vh(viewpoint height)來計算總體視窗的高度(1vh等於視窗高度的1%),而後減去底部footer的高度,從而求得內容區域的最小高度。例如咱們能夠添加以下樣式:spa
.content{ min-height:calc(100vh-footer的高度); box-sizing:border-box; }
從而這個問題就解決了,可是若是頁面的footer高度不一樣怎麼辦?每個頁面都要從新計算一次,這是很麻煩的,因此這種方法雖然簡單但倒是不推薦的。設計
2、使用flex佈局code
這種方法就是利用flex佈局對視窗高度進行分割。footer的flex設爲0,這樣footer得到其固有的高度;content的flex設爲1,這樣它會充滿除去footer的其餘部分。htm
代碼以下:blog
body { display: flex; flex-flow: column; min-height: 100vh; } .content { flex: 1; } .footer{ flex: 0; }
這樣的佈局簡單使用,比較推薦。文檔
3、在content的外面能夠添加一個wrapper
這種方法就是在content的外面添加一個包裹容易,將html代碼改爲這樣:
<body>
<div class="wrapper">
<div class="content"></div>
</div>
<div class="footer"></div>
</body>
而後添加如下樣式:
html, body, .wrapper { height: 100%; } body > .wrapper { height: auto; min-height: 100%; } .content { padding-bottom: 150px; /* 必須使用和footer相同的高度 */ } .footer { position: relative; margin-top: -150px; /* footer高度的負值 */ height: 150px; clear:both; }
另外,爲了保證兼容性,須要在wrapper上添加clearfix類。其代碼以下:
<body>
<div class="wrapper clearfix">
<div class="content"></div>
</div>
<div class="footer"></div>
</body>
.clearfix{ display: inline-block; } .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
ok,好,完成了,這種方法也比較推薦,但就是加入的代碼比較多,也改變了html的文檔結構。