关于css:CSS两栏布局

4次阅读

共计 968 个字符,预计需要花费 3 分钟才能阅读完成。

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

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>

【作者程度无限,欢送大家在评论区交换斧正~】

正文完
 0