Sticky footers,元素一直在页面底部

331 阅读2分钟

在网页设计中,Sticky footers设计是最古老和最常见的效果之一,大多数人都曾经经历过。它可以概括如下:如果页面内容不够长的时候,页脚块粘贴在视窗底部;如果内容足够长时,页脚块会被内容向下推送。

方法一 :fixed

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sticky footer</title>
<style type="text/css">
*{padding: 0;margin: 0;font-size: 48px}
/* 第一步设置盒子为满屏大小 */
.box{
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
overflow: auto;
background: green;
}
/* 第二步子盒子设置最小高度且清除浮动 给一个padding-bottom 等于footer 避免内容被footer遮盖*/
.box .main{
width: 100%;
min-height: 100%;  

padding-bottom: 100px;
}
.box .main .content{
background: orange;
/*padding-bottom: 100px;*/
}
/* 第三步footer的高度和margin-top要相等 */
.box .footer{
position: relative;
width: 100%;
height: 100px;
background: #f3f3f3;
margin: -100px auto 0 auto;
clear: both;
text-align: center;
line-height: 100px;

}
.clearfix{
display: inline-block;

}
.clearfix::after{
content: ".";
display: block;
height: 0;
line-height: 0;
visibility: hidden;
clear: both;
}
</style>
</head>
<body>
<div class="box">
<div class="main clearfix">
<div class="content">
<p>这里是内容区域</p>
<p>这里是内容区域</p>
<p>这里是内容区域</p>
<p>这里是内容区域</p>
<p>这里是内容区域</p>
<p>这里是内容区域</p>
<p>这里是内容区域</p> 
</div>
</div>
<div class="footer">这是footer区域</div>
</div>
</body>
</html>

方法二,flexbox

<html>
<head>
<style>
    body { 
        display: flex; flex-flow: column; min-height: 100vh;
    }
    main{flex:1}
    header,footer{height:80px;}
</style>
</head>
<body>
<header> 
   <h1>Site name</h1>
</header> 
<main> 
  <p>Bacon Ipsum dolor sit amet... <!-- Filler text from baconipsum.com -->
  </p>
</main>
<footer> 
  <p> © 2015 No rights reserved.</p> <p>Made with ♥ by an anonymous pastafarian.</p> 
</footer>
</body>
</html>

我们需要在页头和页脚设置高度,但其内容的高度自动伸缩的来适配剩余空间。我们可以在main上设置flex值大于0(常用的是1)。
flex属性是flex-grow、flex-shrink和flex-basis三个属性缩写。
任何元素设置了flex大于0,元素就会灵活的控制自己的尺寸,来适配容器的剩余空间。
例如,如果main设置了flex:2,footer设置了flex:1,那么页脚的高度是主内容高度的二分之一,同样的,如果值设置的是4和2而不是2和1,他们效果是一样的,因为他们的倍数比例值一样。