弹性盒子高度自适应

880 阅读1分钟

需求:

1、元素高度盛满屏幕,不允许出现滚动条

2、头部占用高度不固定,内容区等于剩余高度

3、内容区内部等同第二条,实现自适应

<!DOCTYPE html>
<html lang="en"><head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>盒子自适应</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .body-box {
            height: 100vh;
            display: flex;
            flex-direction: column;
            padding: 10px;
            box-sizing: border-box;
        }
        
        .screen-header {
            flex-shrink: 0;
            background: red;
            padding: 30px;
            margin-bottom: 10px;
        }
        
        .screen-container-wrap {
            flex: auto;
            /* 必加,浏览器兼容 */
            height: 0;
        }
        
        .screen-container:first-child {
            height: 52%;
            background: blue;
        }
        
        .screen-container:last-child {
            height: calc(48% - 10px);
            margin-top: 10px;
            background: green;
        }
    </style>
</head><body>
    <div class="body-box">
        <div class="screen-header"></div>
        <div class="screen-container-wrap">
            <div class="screen-container"></div>
            <div class="screen-container"></div>
        </div>
    </div>
</body>
</html>

效果:

1.gif