1. 程式人生 > 其它 >css底部固定的5種方法

css底部固定的5種方法

本文主要介紹一個Footer元素如何粘住底部,使其無論內容多或者少,Footer元素始終緊靠在瀏覽器的底部。我們知道,當內容足夠多可以撐開底部到達瀏覽器的底部,如果內容不夠多,不足以撐開元素到達瀏覽器的底部時,下面要講的佈局就是解決如何使元素粘住瀏覽器底部。

方法一:全域性增加一個負值下邊距等於底部高度

有一個全域性的元素包含除了底部之外的所有內容。它有一個負值下邊距等於底部的高度。

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等於底部的高度,來防止內容覆蓋到底部的元素。這個push元素是智慧的,它並沒有佔用到底部的利用,而是通過全域性加了一個負邊距來填充。

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

雖然這個程式碼減少了一個.push的元素,但還是需要增加多一層的元素包裹內容,並給他一個內邊距使其等於底部的高度,防止內容覆蓋到底部的內容。

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;
}

方法三:使用calc()計算內容的高度

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,防止緊靠在一起。

方法四:使用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;
}

https://www.98891.com/article-22-1.html

方法五:使用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;
}

grid早於flexbox出現,但並沒有flexbox被廣泛支援,你可能在chrome Canary或者Firefox開發版上才可以看見效果。