1. 程式人生 > >底部粘連(stiky footer)布局

底部粘連(stiky footer)布局

ont gree architect play 足夠 經歷 arc mage http

前面的話

  在網頁設計中,Sticky footers設計是最古老和最常見的效果之一,大多數人都曾經經歷過。它可以概括如下:如果頁面內容不夠長的時候,頁腳塊粘貼在視窗底部;如果內容足夠長時,頁腳塊會被內容向下推送。本文將詳細介紹sticky footer的4種實現方式

絕對定位

  常見的實現方法是對(.sticky)footer進行絕對定位,假設高度為50px。對父級(.box)進行相對定位,將html、body的高度設置為100%,父級(.box)的最小高度設置為100%,將(.content)內容部分設置padding-bottom為footer的高度,即50px,這裏不用margin-bottom是因為會出現margin-bottom傳遞的情況

  [註意]關於margin傳遞的詳細情況移步至此

<style>
html,body{height:100%}
body{margin:0}
.box{position:relative;background-color:lightblue;min-height:100%;}
.content{padding-bottom:50px;}
.sticky{position:absolute;background-color:lightgreen;width:100%;height:50px;bottom:0;}
</style>
<div class="box"
> <main class="content"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quam eos architecto ratione culpa adipisci inventore ipsum eum esse, nam aperiam, non tempora perferendis doloribus cumque ducimus quidem consequuntur reprehenderit reiciendis! ... </main> <footer class
="sticky"></footer> </div>

  效果如下

技術分享圖片

calc

  上面的代碼中,因為要實現最小高度100%的效果,給html、body都設置為高度100%,不利於代碼擴展。下面使用100vh來代替100%,代碼會簡潔很多。內容部分(.content)設置最小高度為calc(100vh - 50px)即可

  [註意]關於視口單位vh的詳細信息移步至此,關於calc的詳細信息移步至此

<style>
body{margin:0}
.content{background-color:lightblue;min-height: calc(100vh - 50px)}
.sticky{background-color:lightgreen;height:50px;}
</style>
<div class="box">
  <main class="content">
    Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quam eos architecto ratione culpa adipisci inventore ipsum eum esse, nam aperiam, non tempora perferendis doloribus cumque ducimus quidem consequuntur reprehenderit reiciendis!
    ...
  </main>
  <footer class="sticky"></footer>
</div>

  效果如下

技術分享圖片

flex

  上面的代碼中,如果sticky的底部高度發生了變化,則內容部分的代碼也需要進行相應地調整。如果使用flex,則可以更加靈活。為父級(.box)設置flex、上下排列及最小高度為100vh,為內容部分(.content)設置flex:1即可

  [註意]關於flex的詳細信息移步至此

<style>
body{margin:0}
.box{display:flex;flex-flow:column;min-height:100vh;background-color:lightblue;}
.content{flex:1;}
.sticky{background-color:lightgreen;height:50px;}
</style>

grid

  作為最新布局方式的grid當然也可以實現,而且代碼更加簡潔

  [註意]關於grid的詳細信息移步至此

<style>
body{margin:0}
.box{display:grid;grid-template-rows:1fr 50px;min-height:100vh;}
.content{background-color:lightblue;}
.sticky{background-color:lightgreen;}
</style>

底部粘連(stiky footer)布局