Skip to content

【转载】CSS 粘住固定底部的5种方法

方法一:全局增加一个负值下边距等于底部高度

有一个全局的元素包含除了底部之外的所有内容。它有一个负值下边距等于底部的高度,就像这个演示链接

HTML代码

html
<body>
  <div class="wrapper">
    content

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

CSS代码:

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 代码:

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

CSS

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

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

CSS:

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

演示:

给 70px 而不是 50px 是为了为了跟底部隔开 20px,防止紧靠在一起。

方法四:使用flexbox

关于 flexbox 的教程,还请查看之前的一篇详细的教程

HTML:

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

CSS:

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

演示:

方法五:使用 grid 布局

HTML:

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

CSS:

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 开发版上才可以看见效果