什麼是Sticky footer佈局?
前端開發中大部分網站,都會把一個頁面分爲頭部區塊、內容區塊、頁腳區塊,這也是比較。每每底部都要求能固定在屏幕的底部,而非隨着文檔流排布。要實現的樣式能夠歸納以下:若是頁面內容不夠長的時候,頁腳區塊在屏幕的底部;若是內容足夠長的時候,頁腳區塊會被內容向下推送。能夠如下圖展現Sticky footer實現的效果:css
在正常的文檔流中,頁面內容較少的時候,若是不作處理,頁腳部分不是固定在視窗底部的。html
使用sticky footer佈局達到了預期的效果,及時內容區較少,頁腳區塊也是固定在底部。前端
實現方式
首先構建簡單的佈局代碼:瀏覽器
<body> <div class="content"></div> <div class="footer"></div> </body>
其中content爲內容區。方法介紹。
1、爲內容區域添加最小高度
這種方法重要用vh(viewpoint height)來計算總體視窗的高度(1vh等於視窗高度的1%),而後減去底部footer的高度,從而求得內容區域的最小高度。例如咱們能夠添加以下樣式:app
.content { min-height: calc(100vh-footer的高度) }
此方法須要知道footer的高度,若是高度不肯定此方法不推薦。content的高度也能夠用百分比來表示。佈局
2、flex佈局方式
html代碼:flex
body { display: flex; flex-flow: column; min-height: 100vh; } .content { flex: 1; } .footer{ flex: 0; }
這種方法就是利用flex佈局對視窗高度進行分割。footer的flex設爲0,這樣footer得到其固有的高度;content的flex設爲1,這樣它會充滿除去footer的其餘部分。網站
2、負margin佈局方式實現
基本構架:
html代碼spa
<div class="wrapper clearfix"> <div class="content"> // 這裏是頁面內容 </div> </div> <div class="footer"> // 這裏是footer的內容 </div>
css代碼:code
.wrapper { min-height: 100%; } .wrapper .content{ padding-bottom: 50px; /* footer區塊的高度 */ } .footer { position: relative; margin-top: -50px; /* 使footer區塊正好處於content的padding-bottom位置 */ height: 50px; clear: both; } .clearfix::after { display: block; content: "."; height: 0; clear: both; visibility: hidden; }
須要注意的:content元素的padding-bottom與footer元素的高度以及footer元素的margin-top值必需要保持一致。這種負margin的佈局方式,是兼容性最佳的佈局方案,各大瀏覽器都可完美兼容,適合各類場景,但使用這種方式的前提是必需要知道footer元素的高度,且結構相對較複雜。