sticky-footer的三种解决方案

时间:2023-01-01 00:04:15

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

sticky-footer的三种解决方案  sticky-footer的三种解决方案

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

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

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

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

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

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

  从而这个问题就解决了,但是如果页面的footer高度不同怎么办?每一个页面都要重新计算一次,这是很麻烦的,所以这种方法虽然简单但却是不推荐的。

  二、使用flex布局

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

  代码如下:

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

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

  三、在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:;
clear: both;
visibility: hidden;
}

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