Flex布局实现头尾固定、中间内容自适应

头尾固定,中间区域可以滑动效果是移动端最常见的效果,以京东页面为例。以前开发时常用的方法是用固定布局position:fixed;实现,但是该方法在ios上或者其他机型上会出现问题。现在,可以用flex方法快速实现该布局

Flex布局实现头尾固定、中间内容自适应

<div class="wrap">
       <div class="header">头部</div>
       <div class="content">中间内容区域</div>
       <div class="footer">尾部</div>
</div>
html,body{
    height: 100%;    /* 很重要 */
}
.wrap{
    width: 100%;
    height: 100vh;     /* 很重要,如果设置成100%,页面内容过多时不会固定 */
    display: flex;
    flex-direction: column;
    font-size: 16px;
}
.header{
    background: aquamarine;
    height: 60px;
}
.content{
    flex: 1;    /* 很重要 */
    overflow-y:auto; /* 很重要,否则当该内容超过一屏时,尾部区域不会固定 */
    background: #4CAF50;
}
.footer{
    background: tan;
    height: 40px;
}

/* 让内容居中显示 */
.header,.content,.footer{
    display: flex;
    align-items: center;
    justify-content: center;
}

运行效果:
Flex布局实现头尾固定、中间内容自适应
说明:css样式中,一定要设置html,body以及最外层包裹容器的高度为100%,同时中间内容区域的样式一定要添加flex:1;以及overflow-y:auto;

猜你喜欢

转载自blog.51cto.com/15142266/2669254