CSS實現Footer置底的五種方式的分享

來源:互聯網
上載者:User
頁尾置底(Sticky footer)就是讓網頁的footer部分始終在瀏覽器視窗的底部。

當網頁內容足夠長以至超出瀏覽器可視高度時,頁尾會隨著內容被推到網頁底部;
但如果網頁內容不夠長,置底的頁尾就會保持在瀏覽器視窗底部。

方法一:將內容部分的margin-bottom設為負數

<p class="wrapper">    <!-- content -->    <p class="push"></p></p><p class="footer">footer</p>
html, body {  margin: 0;  padding: 0;  height: 100%;}.wrapper {  min-height: 100%;    margin-bottom: -50px; /* 等於footer的高度 */}.footer, .push {  height: 50px;}
  1. 這個方法需要容器裡有額外的佔位元素(p.push)。

  2. p.wrappermargin-bottom需要和p.footer-height值一樣,注意是負height

方法二:將頁尾的margin-top設為負數

  • 給內容外增加父元素,並讓內容部分的padding-bottom與頁尾的height相等。

<p class="content">  <p class="content-inside">    <!-- content -->  </p></p><p class="footer">footer</p>
html, body {  margin: 0;  padding: 0;  height: 100%;}.content {  min-height: 100%;}.content-inside {  padding: 20px;  padding-bottom: 50px;}.footer {  height: 50px;  margin-top: -50px;}

方法三:使用calc()設定內容高度

<p class="content">  <!-- content --></p><p class="footer">footer</p>
.content {  min-height: calc(100vh - 70px);}.footer {  height: 50px;}
  • 這裡假設p.contentp.footer之間有20px的間距,所以70px=50px+20px

方法四:使用flexbox彈性盒布局

以上三種方法的footer高度都是固定的,如果footer的內容太多則可能會破壞布局。

<p class="content">  <!-- content --></p><p class="footer">footer</p>
html {  height: 100%;}body {  min-height: 100%;  display: flex;  flex-direction: column;}.content {  flex: 1;}

方法五:使用Grid網格布局

<p class="content">  <!-- content --></p><p class="footer">footer</p>
html {  height: 100%;}body {  min-height: 100%;  display: grid;  grid-template-rows: 1fr auto;}.footer {  grid-row-start: 2;  grid-row-end: 3;}
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.