sticky-footer的5种实现方式

sticky-footer的目的是将footer“定”到浏览器窗口的底部。如果页面上有足够的内容撑开footer仍然会挂在页面的最底部。但是如果页面上的内容很短,footer仍会定位在浏览器窗口的底部。

1. margin-bottom负值

除了页脚之外,还需要有一个父级标签可以包裹所有内容。它的负边距等于页脚的高度。

<body>
  <div class="wrapper">

      content

    <div class="push"></div>
  </div>
  <footer class="footer"></footer>
</body>
html, body {
  height: 100%;
  margin: 0;
}
.wrapper {
  min-height: 100%;
  margin-bottom: -50px;
}
.footer,
.push {
  height: 50px;
}

这个内容区域内需要一个额外的元素(“ .push”),以确保负边距不会拉起页脚并覆盖任何内容。

2.margin-top负值

不需要占位的push元素,但是需要在内容周围添加额外的包装元素,以在其中应用匹配的底部填充。以防止负边距提升页脚高于任何内容。

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

这种技术与前一种方法都需要额外的不必要的HTML元素。

3.calc()计算

不需要任何额外元素的方法是使用calc()调整包装器高度。只有两个标签,总高度为100%。

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>
.content {
  min-height: calc(100vh - 70px);
}
.footer {
  height: 50px;
}

请注意calc()中的70px与页脚的50px固定高度。这是假设。假设内容中的最后一项具有20px的下限。这是底部边距加上页脚的高度,需要加在一起以从视口高度中减去。我们在这里使用vh作为高度,以避免必须设置100%的body,然后才能设置100%的.content高度。

4.flex实现

上述三种技术的主要问题是它们需要固定高度的页脚。固定高度布局上不够优雅,将flexbox用于sticky-footer不仅不需要任何额外的元素,而且可以用于可变高度的footer。

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>
html, body {
  height: 100%;
}
body {
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1 0 auto;
}
.footer {
  flex-shrink: 0;
}

甚至可以在下面添加一个或更多内容的标题。flexbox的技巧是:

  • flex: 1 设置主要内容。
  • 或者margin-top: auto

flex教程

5.grid实现

网格布局比flexbox 兼容性差一些。查看教程

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

此演示应该可以在Chrome Canary或Firefox Developer Edition中使用,并且可能会被反向移植到Edge的旧版网格布局: