CSS两栏布局
Chao 工程师

一般两栏布局指的是左边一栏宽度固定,右边一栏宽度自适应

  1. 浮动 + margin

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    .outer, .left, .right {
    height: 100px;
    }
    .left {
    float: left;
    width: 200px;
    background: tomato;
    }
    .right {
    margin-left: 200px;
    width: auto;
    background: gold;
    }
  2. 浮动 + 右盒子BFC

    利用浮动,左侧元素设置固定大小,并左浮动,右侧元素设置overflow: hidden; 这样右边就触发了BFC,BFC的区域不会与浮动元素发生重叠,所以两侧就不会发生重叠。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    .left {
    width: 100px;
    background: red;
    float: left;
    }

    .right {
    background: blue;
    overflow: hidden;
    }
  3. 父元素相对定位,左子元素绝对定位(跟“1”对应)

    将父级元素设置为相对定位。左边元素设置为absolute定位,并且宽度设置为200px。将右边元素的margin-left的值设置为200px。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    .outer,
    .left,
    .right {
    height: 100px;
    }

    .outer {
    position: relative;
    }

    .left {
    position: absolute;
    width: 200px;
    background: tomato;
    }

    .right {
    margin-left: 200px;
    background: gold;
    }
  4. 利用绝对定位,将父级元素设置为相对定位。左边元素宽度设置为200px,右边元素设置为绝对定位,左边定位为200px,其余方向定位为0。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    .outer {
    position: relative;
    height: 100px;
    }
    .left {
    width: 200px;
    background: tomato;
    }
    .right {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 200px;
    background: gold;
    }
  5. 利用flex布局,将左边元素设置为固定宽度200px,将右边的元素设置为flex:1。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    .outer {
    display: flex;
    height: 100px;
    }
    .left {
    width: 200px;
    background: tomato;
    }
    .right {
    flex: 1;
    background: gold;
    }
 Comments