Stick footers布局总结

一、Sticky footers解释

在网页设计中,Sticky footers设计是最古老和最常见的效果之一,大多数人都曾经经历过。它可以概括如下:如果页面内容不够长的时候,页脚块粘贴在视窗底部;如果内容足够长时,页脚块会被内容向下推送。(效果如下图)

 

二、实现

2.1 容器使用负的margin bottom

 首先是个包裹除了footer之外其他元素的容器,然后容器内有个占位元素,以及使用负的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;
}

 

2.2 底部使用负的margin bottom

 既然想到在容器上使用负的margin bottom,同理可得负的margin top版本

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

2.3 calc版本

  结合vh单位,calc 版本就粗暴很多。

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

calc中的 70px,和50px是假定了content中最后一个元素有个20px的margin bottom,你不必在意这些~

2.4 flexbox版本

  flexbox版本同样很简单,并且相比前面三种方式,它不需要知道footer的高度,避免了Magic Number的尴尬。

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

原理是flex: 1使得content的高度可以自由伸缩。

2.5 grid版本

  grid比flexbox还要新很多,使用grid同样很简洁,遗憾的是现在Chrome Canary 或者 Firefox Developer Edition才能看到效果。

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

文章转自:  http://w3ctrain.com/2016/06/24/stick-footer/

 

posted @ 2017-07-01 09:43  奔跑的蜗牛~  阅读(576)  评论(0编辑  收藏  举报