天天看点

css布局两边固定中间自适应的常用方法css布局两边固定中间自适应

css布局两边固定中间自适应

<h2>1、利用自身浮动</h2>
  <p>左右浮动两块div元素,脱离标准流,中间那块元素就会上去,跟他们一行,利用margin留出左右宽度</p >
  <div class=box1>
    <div class="boxLeft">左边</div>
    <div class="boxRight">右边</div>
    <!-- 注意这个div一定要放最下面 -->
    <div class="boxCenter">中间</div>
  </div>
<style>
    /* 1、利用自身浮动 */
    .boxLeft{
      min-height: 100px;
      width: 200px;
      background: #987;
      float: left;
    }
    .boxRight{
      min-height: 100px;
      width: 300px;
      background: #369;
      float: right;
    }
    .boxCenter{
      min-height: 100px;
      margin-left: 220px;
      margin-right: 320px;
      background: #192;
    }
           
<h2>2、利用绝对定位</h2>
  <p>左右绝对定位的两块div元素,脱离标准流,中间那块元素就会上去,跟他们一行,利用margin留出左右宽度</p >
  <div class=box2>
    <div class="boxLeft2">左边</div>
    <div class="boxRight2">右边</div>
    <div class="boxCenter2">中间</div>
  </div>
  /* 2、利用绝对定位 */
    .boxLeft2{
      min-height: 100px;
      width: 200px;
      background: #987;
      position: absolute;
      left: 0;
    }
    .boxRight2{
      min-height: 100px;
      width: 300px;
      background: #369;
      position: absolute;
      right: 0;
    }
    .boxCenter2{
      min-height: 100px;
      margin-left: 220px;
      margin-right: 320px;
      background: #192;
    }
 
           
<h2>3、利用弹性布局</h2>
  <p>设置flex:1;可以自适应剩余空间</p >
  <div class=box3>
    <div class="boxLeft3">左边</div>
    <!-- 注意这个div一定要放中间 -->
    <div class="boxCenter3">中间</div>
    <div class="boxRight3">右边</div>
  </div>
/* 3、利用弹性布局 */
    .box3{
      display: flex;
    }
    .boxLeft3{
      min-height: 100px;
      width: 200px;
      background: #987;
    }
    .boxRight3{
      min-height: 100px;
      width: 300px;
      background: #369;
    }
    .boxCenter3{
      min-height: 100px;
      margin: 0 20px;
      background: #192;
      flex: 1;
    }
           
<h2>4、利用display:table;</h2>
  <div class=box4>
    <div class="boxLeft4">左边</div>
    <!-- 注意这个div一定要放中间 -->
    <div class="boxCenter4">中间</div>
    <div class="boxRight4">右边</div>
  </div>
 /* 4、利用display */
    .box4{
      display: table;
      width: 100%;
    }
    .boxLeft4{
      min-height: 100px;
      width: 200px;
      background: #987;
      display: table-cell;
    }
    .boxCenter4{
      min-height: 100px;
      background: #192;
      margin: 0 20px;
    }
    .boxRight4{
      min-height: 100px;
      width: 300px;
      background: #369;
      display: table-cell;
    }