sticky footer布局

 【转】原地址:https://segmentfault.com/a/1190000012794431

Sticky footers设计是最古老和最常见的效果之一,它可以概括如下:

1 如果页面内容不够长的时候,页脚块粘贴在视窗底部;
2 如果内容足够长时,页脚块会被内容向下推送。

出现问题如图:
当内容过少时,页脚内容也无法在视窗底部
当内容过多时,页脚内容无法在视窗底部

方法一:经典固定高度套路
·html内容:

<body>
    <div class="wrapper">
        <div class="content">这里是content</div>
    </div> 
  <div class="footer"></div>
</body>

为内容区域添加外层包裹的wrapper,设置css样式
·css内容:

html, body, .wrapper {
 height: 100%;
}
body > .wrapper {
     height: auto;
     min-height: 100%;
}
.content {
     /* 必须使用和footer相同的高度 为底部留白 */
    padding-bottom: 150px;
}  
.footer {
    position: relative;
    /* footer高度的负值 */
    margin-top: -150px; 
    height: 150px;
    clear:both;
}
重要的是需要设置min-height:100%,内容区域padding-bottom: 150px;尾部margin-top: -150px; 
这个方法兼容性很好,实测 IE7 也能正常展示,为了更好的兼容性,可以为wrapper添加清除浮动
    .clearfix{
         display: inline-block;
    }
    .clearfix:after {
         content: ".";
         display: block;
         height: 0;
         clear: both;
         visibility: hidden;
    }

方法二:Flexbox布局
html:

<div class="content">
  <p>内容区域</p>
</div>
<div class="footer">
  <p>页脚块</p>
</div>

css:

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

这个方法精简,当然缺点也是显而易见的,只有 IE10 及以上的浏览器才支持 flex 布局
方法三:内容区域计算最小的高度

这种方法通过vh(viewpoint height)来计算整体视窗的高度(1vh等于视窗高度的1%),然后减去底部footer的高度,从而求得内容区域的最小高度。

html:

<body>
  <div class="content">
      <p>所有内容区</p>
  </div>
  <div class="footer"></div>
</body>

css:

 
.content{
 min-height:calc(100vh - 7em);
 box-sizing:border-box;
} 
.footer{
    height:7em;
    width:100%;
}
posted @ 2018-05-22 15:51  这个男人  阅读(124)  评论(0编辑  收藏  举报