使用 flexbox 将 footer 保持在底部

布局网页时, 有时页面内容太少,无法将内容区域撑开,从而在 footer 下面留下一大块空白。

 
 

解决方法 flexbox

HTML

<body>
    <header>...</header>
    <section class="main-content">...</section>
    <footer>...</footer>
</body>

CSS

html{
    height: 100%;
}

body{
    display: flex;
    flex-direction: column;
    height: 100%;
}

header{
   /* 我们希望 header 采用固定的高度,只占用必须的空间 */
   /* 0 flex-grow, 0 flex-shrink, auto flex-basis */
   flex: 0 0 auto;
}

.main-content{
   /* 将 flex-grow 设置为1,该元素会占用全部可使用空间 
      而其他元素该属性值为0,因此不会得到多余的空间*/
   /* 1 flex-grow, 0 flex-shrink, auto flex-basis */
   flex: 1 0 auto;
}

footer{
   flex: 0 0 auto;
}

兼容性

所有的主流浏览器都支持 flexbox,就 IE 来说,IE9以后的版本都是支持的。



原文地址:https://www.cnblogs.com/woniu666/p/13320616.html