5種實現(xiàn)CSS底部固定的方法

我們經(jīng)常會遇到到需要實現(xiàn)底部固定控件的界面,比如詳情頁,下面就羅列5個常用的方法

方法1:全局增加一個負值下邊距等于底部高度

有一個全局的元素包含除了底部之外的所有內(nèi)容。它有一個負值下邊距等于底部的高度。
html代碼:

<body>
  <div class="wrapper">
      content
    <div class="push"></div>
  </div>
  <footer class="footer"></footer>
</body>

CSS代碼:

html, body {
  height: 100%;
  margin: 0;
}
.wrapper {
  min-height: 100%;

  /* Equal to height of footer */
  /* But also accounting for potential margin-bottom of last child */
  margin-bottom: -50px;
}
.footer, 
.push {
  height: 50px;
}

這個代碼需要一個額外的元素.push等于底部的高度,來防止內(nèi)容覆蓋到底部的元素。這個push元素是智能的,它并沒有占用到底部的利用,而是通過全局加了一個負邊距來填充。

方法2:底部元素增加負值上邊距

雖然這個代碼減少了一個.push的元素,但還是需要增加多一層的元素包裹內(nèi)容,并給他一個內(nèi)邊距使其等于底部的高度,防止內(nèi)容覆蓋到底部的內(nèi)容。
HTML代碼:

<body>
  <div class="content">
    <div class="content-inside">
      content
    </div>
  </div>
  <footer class="footer"></footer>
</body>

CSS:

html, body {
  height: 100%;
  margin: 0;
}
.content {
  min-height: 100%;
}
.content-inside {
  padding: 20px;
  padding-bottom: 50px;
}
.footer {
  height: 50px;
  margin-top: -50px;
}

方法3:使用calc()計算內(nèi)容的高度

HTML

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

.content {
  min-height: calc(100vh - 70px);
}
.footer {
  height: 50px;
}

給70px而不是50px是為了為了跟底部隔開20px,防止緊靠在一起。

方法4:使用flexbox

HTML:

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

html {
  height: 100%;
}
body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
}

方法5:使用grid布局

HTML:

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

html {
  height: 100%;
}
body {
  min-height: 100%;
  display: grid;
  grid-template-rows: 1fr auto;
}
.footer {
  grid-row-start: 2;
  grid-row-end: 3;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容