footer的设置绝不只是设置footer:使html高、宽自适应
有时候页面内容无法填满页面,又需要让footer保持了网页最末尾,而且能在网页大小变化时,跟随位置变换,而不挡住内容。
目前网上的方法很多提到了使用固定footer的位置的设置来使footer始终在末尾,但是没有交代如果网页的内容并不能填满整个空间时,该如何让footer保持在网页的最底部。
针对这一问题,我自己的解决方法是,对html,body,以及footer的父级进行设置,规定最小高度,使其填满整个网页。再加上footer固定位置的设置,就能够使footer始终保持在网页最底部。
具体方法如下:
1. html和body首先需要铺满整个页面
使html高度自适应:使用height: auto !important;
同时,使用min-height来限制最小的页面高度,避免因为内容不足而导致的页面不能填满
html {
margin: 0;
min-height: 978px;
height: auto !important;
height: 978px;
}
body {
height: 100%;
min-width: 100%;
min-height: 978px;
margin:0;
font-family: Arial;
padding: 10px;
background: #f1f1f1;
}
2. footer的父级需要铺满页面,且留出footer大小变换时的空间。
这需要一方面约定height为100%另外最好也给定最小高度防止无法铺满整个页面。预留空间使用padding-bottom根据自己的需求留出足够的高度。
.mainContainer{
padding-top: 10px;
padding-bottom: 20px;
min-height:978px;
width: 100%;
height: 100%;
position:relative;
padding-bottom: 200px;
}
之后按照内容的比例来分配主内容框中各个部分所占的比例,比如header占10%的高度就写成:
.header {
padding: 5px;
height: 10%;
border-radius: 25px;
background-color: #f1f1f1;
}
注:添加border-radius圆角使框框更美观
3. footer设置高度占比后,位置要设置固定
position:absolute;
bottom:0px;
left:0px;
固定位置后footer就不会因为前面有空而跑上去了
.footer {
padding: 5px;
height: 12%;
width: 100%;
position:absolute;
bottom:0px;
left:0px;
text-align: center;
background: #ddd;
margin-top: 2%;
border-radius: 25px;
}
实例图
以下图片为:受到页面尺寸变化导致内容占比改变时,footer始终能保持在最下方