1

布局是面试中和实际开发中经常遇到的问题,常见的有两栏布局、三栏布局等。想起来之前的一次某团的面试,要求用尽可能多的方法实现左侧固定宽度、右侧自适应的两栏布局,现整理一份最常见的实现两栏布局的几种方法,简单易懂,可作为前端面试准备资料。

0.HTML结构如下:
    <div class="main">
        <div class="left">
        </div>
        <div class="right">
        </div>
    </div>
1.利用浮动float
    <style>
        .main {
            overflow: hidden;
        }
        .left {
            /* 左栏设置左浮动 */
            float: left;
            width: 400px;
            height: 500px;
            background: red;
        }
        .right {
            /* 右栏设置一个左外间距,值为左栏的宽度 */
            margin-left: 400px;
            background: blue;
            height: 500px;
        }
    </style>
2.利用定位position
    <style>
        /* 子绝父相 */
        .main {
            overflow: hidden;
            position: relative;
        }
        .left {
            position: absolute;
            left: 0;
            top: 0;
            width: 400px;
            height: 500px;
            background: red;
        }
        .right {
            /* 右栏设置一个左外间距,值为左栏的宽度 */
            margin-left: 400px;
            height: 500px;
            background: blue;
        }
    </style>
3.利用弹性布局flex
    <style>
        .main {
            display: flex;
        }
        .left {
            height: 500px;
            background: red;
            flex: 0 0 400px
        }
        .right {
            background: blue;
            height: 500px;
            flex: 1;
        }
    </style>
4.利用表格布局table
    <style>
        .main {
            display: table;
            width: 100%;
        }
        .left {
            display: table-cell;
            width: 400px;
            height: 500px;
            background: red;
        }
        .right {
            display: table-cell;
            background:blue;
            height: 500px;
        }
    </style>

【作者水平有限,欢迎大家在评论区交流指正~】


AlbertZX
33 声望3 粉丝

小白前端开发工程师