CSS五种方式实现Footer置底

GlaIFG 7年前
   <p>页脚置底(Sticky footer)就是让网页的footer部分始终在浏览器窗口的底部。</p>    <p>当网页内容足够长以至超出浏览器可视高度时,页脚会随着内容被推到网页底部;</p>    <p>但如果网页内容不够长,置底的页脚就会保持在浏览器窗口底部。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/5819a23cd43bc2ba93a5a0d0d14e5559.png"></p>    <h2>方法一:将内容部分的 margin-bottom 设为负数</h2>    <pre>  <code class="language-css"><div class="wrapper">      <!-- content -->      <div class="push"></div>  </div>  <div class="footer">footer</div></code></pre>    <pre>  <code class="language-css">html, body {    margin: 0;    padding: 0;    height: 100%;  }  .wrapper {    min-height: 100%;      margin-bottom: -50px; /* 等于footer的高度 */  }  .footer, .push {    height: 50px;  }</code></pre>    <ol>     <li> <p>这个方法需要容器里有额外的占位元素( div.push )。</p> </li>     <li> <p>div.wrapper 的 margin-bottom 需要和 div.footer 的 -height 值一样,注意是负 height 。</p> </li>    </ol>    <h2>方法二:将页脚的 margin-top 设为负数</h2>    <ul>     <li> <p>给内容外增加父元素,并让内容部分的 padding-bottom 与页脚的 height 相等。</p> </li>    </ul>    <pre>  <code class="language-css"><div class="content">    <div class="content-inside">      <!-- content -->    </div>  </div>  <div class="footer">footer</div></code></pre>    <pre>  <code class="language-css">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;  }</code></pre>    <h2>方法三:使用 calc() 设置内容高度</h2>    <pre>  <code class="language-css"><div class="content">    <!-- content -->  </div>  <div class="footer">footer</div></code></pre>    <pre>  <code class="language-css">.content {    min-height: calc(100vh - 70px);  }  .footer {    height: 50px;  }</code></pre>    <ul>     <li> <p>这里假设 div.content 和 div.footer 之间有20px的间距,所以70px=50px+20px</p> </li>    </ul>    <h2>方法四:使用flexbox弹性盒布局</h2>    <p>以上三种方法的footer高度都是固定的,如果footer的内容太多则可能会破坏布局。</p>    <pre>  <code class="language-css"><div class="content">    <!-- content -->  </div>  <div class="footer">footer</div></code></pre>    <pre>  <code class="language-css">html {    height: 100%;  }  body {    min-height: 100%;    display: flex;    flex-direction: column;  }  .content {    flex: 1;  }</code></pre>    <h2>方法五:使用Grid网格布局</h2>    <pre>  <code class="language-css"><div class="content">    <!-- content -->  </div>  <div class="footer">footer</div></code></pre>    <pre>  <code class="language-css">html {    height: 100%;  }  body {    min-height: 100%;    display: grid;    grid-template-rows: 1fr auto;  }  .footer {    grid-row-start: 2;    grid-row-end: 3;  }</code></pre>    <p> </p>    <p>来自:https://segmentfault.com/a/1190000008516654</p>    <p> </p>