三栏布局 左右定宽 中间自适应

370 阅读1分钟

一、利用浮动

HTML

<div class="left"></div>
<div class="right"></div>
<div class="center"></div>

CSS

    div {
      height: 200px;
    }
    .left {
      float: left;
      background-color: blue;
      width: 200px;
    }
    .right {
      float: right;	
      background-color: red;
      width: 200px;
    }
    .center {
      background-color: pink;
      margin: 0 200px;
    }

左右两个盒子分别左浮动与又浮动,中间的盒子的左右margin分别对应左右盒子的宽度就行了,唯一需要注意的是center盒子要写在两个盒子之后,因为如果不是这样的话center会独自占一行,从而把right盒子挤下去。

二、利用定位

HTML

<div class="outer">
  <div class="left"></div>
  <div class="right"></div>
  <div class="center"></div>
</div>

CSS

    div {
      height: 200px;
    }

    .outer {
      position: relative;
    }

    .left {
      position: absolute;
      top: 0;
      left: 0;
      background-color: blue;
      width: 200px;
    }

    .right {
      position: absolute;
      top: 0;
      right: 0;
      background-color: red;
      width: 200px;
    }

    .center {
      background-color: pink;
      margin: 0 200px;
    }

和上面的浮动实现方法类似,只不过利用定位将left盒子与right盒子放到左边与右边,center盒子的左右margin也分别的左右两个盒子的宽度

三、flex布局

html

<div id='container'>
    <div class='left'>左侧</div>
    <div class='center'>中间</div>
    <div class='right'>右侧</div>
</div>

css

#container {
    width: 100%;
    display: flex;
}
.left, .right {
    width: 200px;
    background-color: red;
    height: 500px;
}
.center {
    flex: 1;
    height: 500px;
    background-color: yellow;
}