文章目录
  1. 1. 方案一: padding-bottom+负margin-top
  2. 2. 方案二: 使用 flex
  3. 3. 方案三: calc()

Sticky footers 效果: 如果页面内容不够长的情况下,页脚块粘贴在视窗底部;如果内容足够长,页脚块会被内容向下推送。

实现这种效果我尝试了三种解决方案。

方案一: padding-bottom+负margin-top

demo:
html

1
2
3
4
5
6
7
8
<div class="sticky-wrapper">
<div class="content-wrapper ">
<div class="content">
这里是内容。。。。。。。。。。
</div>
</div>
<footer></footer>
</div>

css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.sticky-wrapper {
height: 100vh;
border: solid 1px red;
}
.content-wrapper {
min-height: 100vh;
background: pink;
}
.content {
padding-bottom: 50px;
}
footer {
height: 50px;
margin-top: -50px;
background: green;
}

思想:

使得父元素sticky-wrapper为屏幕的高度,子元素content-wrapper的高度也是屏幕高度,但是其内部子元素设置padding-bottom,这个值等于底部footer的高度。然后设置底部footer,底部footermargin-top是负的footer 高度值,这样就使得footer正好可以填充到padding-bottom所产生的空白处。

这种方法兼容性最好,下面的两种比较方便,但是是css3才支持。

方案二: 使用 flex

demo:
html

1
2
3
4
5
6
<div class="sticky-wrapper">
<div class="content-wrapper ">
这里是内容。。。。。。。。。。
</div>
<footer></footer>
</div>

css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.sticky-wrapper {
display: flex;
flex-flow: column;
min-height: 100vh;
border: solid 1px red;
}
.content-wrapper {
flex: 1;
background: pink;
}
footer {
height: 50px;
background: green;
}

思想:

flex 布局中flex属性为1 时,元素是可以自由伸缩的。

方案三: calc()

demo:
html

1
2
3
4
5
6
<div class="sticky-wrapper">
<div class="content-wrapper ">
这里是内容。。。。。。。。。。
</div>
<footer></footer>
</div>

css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.sticky-wrapper {
border: solid 1px red;
}
.content-wrapper {
<!--注意:“-”号两边必须有空格-->
min-height: calc(100vh - 100px);
background: pink;
}
footer {
height: 50px;
background: green;
}

思想:

使用calc()动态计算内容高度。 对于calc() 的运算规则:

  • 使用“+”、“-”、“*” 和 “/”四则运算

  • 可以使用百分比、px、em、rem等单位

  • 可以混合使用各种单位进行计算

  • 表达式中有“+”和“-”时,其前后必须要有空格

  • 表达式中有“*”和“/”时,其前后可以没有空格,但最好留有空格。

文章目录
  1. 1. 方案一: padding-bottom+负margin-top
  2. 2. 方案二: 使用 flex
  3. 3. 方案三: calc()