问题
许多大型网站都有一个底栏,不论内容的高度是否填满屏幕,底栏都一直在页面的最底部。
这个效果看似简单,却有不少的“坑”,下面我来介绍两种方法解决这个问题。
第一个方法(引用中注释的css)使用了固定定位解决
第二种方法使用的是flex布局解决的
*具体请参考:<<css secret>> -41项 紧贴底部的页脚*
要注意的是第一种方法必须设置外层容器的最小高度为100%
第二种方法使用了flex属性,flex包含三种属性,这里用到flex-grow: 设置放大比例
<!DOCTYPE html>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
background-color: #f3f3f3;
height: 100%;
}
/*
.container {
position: relative;
width: 100%;
min-height: 100%;
}
.content {
width: 100%;
height: 600px;
background: red;
}
.footer {
height: 200px;
width: 100%;
background: yellow;
position: absolute;
bottom: 0;
} */
/*flex 布局 */
.container {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
.content {
width: 100%;
height: 600px;
background: red;
flex: 1 0 auto;
}
.footer {
height: 200px;
width: 100%;
background: yellow;
flex: 0 0 auto;
}
</style>
</head>
<body>
<div class="container">
<div class="content"></div>
<div class="footer"></div>
</div>
</body>
</html>
虽然两种方法都能给我们达到最终的目的,但是在具体效果上还是有些区别
下面放几张图来对比一下。
由于内容受flex-grow: 1的影响,浏览器窗口的尺寸决定了content的尺寸。所以填充的颜色不受height属性影响。
sticky footer下的content的height属性正常