flex布局-保持footer一直在底部

flex布局-保持footer一直在底部

月光魔力鸭

2020-06-04 00:18 阅读 834 喜欢 1 flex

通过flex实现footer 一直停留在底部,不论内容有多少。 在之前的时候,都是通过js来计算高度,调整css的样式,最近做商城来着,想着赶紧学学flex,则不学就落伍了,于是还是碰到了这个问题。

目标

实现footer 不论内容有多少,都要保留在最底部,当内容少的时候,相当于以前的绝对定位,内容多的时候,又会跟随文档流向下移动。

方式

flex 来实现,主要属性为: flex-grow ,涉及到了剩余空间分配问题。

实现

html 部分分为上中下,三部分,属于常见布局。

<html>
<body>
    <header>
        HEADER
    </header>
    <div class="content">
        content
    </div>
    <footer>
        FOOTER
    </footer>
</body>
</html>

css 样式:

html,body{
    height:100%;
    margin:0px;
    padding:0px;
}
/**将父级body设置为flex**/
body{
     display:flex;
    /**布局方向**/
    flex-direction:column;
}

最主要的就是 flex-grow 这个属性,默认为0 ,也就是不占据剩余空间,我们只需要将headerfooter 设置为0,不占据剩余空间,将content设置为1 ,那么剩余空间将会被content全部占据,如下:

header,footer{
    flex: 0 0 auto;
}
.content{
    flex:1 1 auto;
}

结果

结果

示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,body{
            margin:0px;
            padding:0px;
            height:100%;
            width:100%;
        }
        body>div{
            border:1px solid red;
        }
        body{
            display:flex;
            flex-direction: column;
        }
        .content{
            flex: 1 0 auto;
        }
        header{
            height:60px;
            flex:0 0 auto;
            /**增加颜色区分**/
            background-color: #49e;
        }
        footer{
            height:100px;
            flex:0 0 auto;
            /*增加颜色区分*/
            background-color: #f60;
        }
    </style>
</head>
<body>
    <header>
        HEADER
    </header>
    <div class="content">
        content
    </div>
    <footer>
        FOOTER
    </footer>
</body>
</html>

转载请注明出处: https://chrunlee.cn/article/css-footer-be-foot.html


感谢支持!

赞赏支持
提交评论
评论信息 (请文明评论)
暂无评论,快来快来写想法...
推荐
今天遇到一个问题,在chrome ff 等浏览器都挺正常的table,在IE9 和 IE10下边框不显示,直接就没有了。