sticky-footer的三种解决方案

      在网页设计中,Sticky footers设计是最古老和最多见的效果之一,大多数人都曾经经历过。它能够归纳以下:若是页面内容不够长的时候,页脚块粘贴在视窗底部;若是内容足够长时,页脚块会被内容向下推送,咱们看到的效果就以下面两张图这样。这种效果基本是无处不在的,很受欢迎。html

sticky  

 

  那么面对这样的问题有什么解决方法呢?首先咱们先构建简单的代码app

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

  其中content为咱们的内容区。下面开始介绍解决方法。布局

  1、为内容区域添加最小的高度flex

  这种方法重要用vh(viewpoint height)来计算总体视窗的高度(1vh等于视窗高度的1%),而后减去底部footer的高度,从而求得内容区域的最小高度。例如咱们能够添加以下样式:spa

.content{
     min-height:calc(100vh-footer的高度);
     box-sizing:border-box;
}    

  从而这个问题就解决了,可是若是页面的footer高度不一样怎么办?每个页面都要从新计算一次,这是很麻烦的,因此这种方法虽然简单但倒是不推荐的。设计

  2、使用flex布局code

  这种方法就是利用flex布局对视窗高度进行分割。footer的flex设为0,这样footer得到其固有的高度;content的flex设为1,这样它会充满除去footer的其余部分。htm

  代码以下:blog

body { 
    display: flex; 
    flex-flow: column; 
    min-height: 100vh;
 }
 .content {
    flex: 1; 
}
.footer{
    flex: 0;      
}

     这样的布局简单使用,比较推荐。文档

  3、在content的外面能够添加一个wrapper

  这种方法就是在content的外面添加一个包裹容易,将html代码改为这样:

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

  而后添加如下样式:

html, body, .wrapper {
     height: 100%;
}
body > .wrapper {
     height: auto; min-height: 100%;
}
.content {
    padding-bottom: 150px; /* 必须使用和footer相同的高度 */
}  
.footer {
    position: relative;
    margin-top: -150px; /* footer高度的负值 */
    height: 150px;
    clear:both;
}

另外,为了保证兼容性,须要在wrapper上添加clearfix类。其代码以下:

<body>
    <div class="wrapper clearfix">
        <div class="content"></div>
    </div> 
  <div class="footer"></div>
</body>
.clearfix{
     display: inline-block;
}
.clearfix:after {
     content: ".";
     display: block;
     height: 0;
     clear: both;
     visibility: hidden;
}    

ok,好,完成了,这种方法也比较推荐,但就是加入的代码比较多,也改变了html的文档结构。

相关文章
相关标签/搜索