宽度自适应的n种方法

左边div固定宽度,右边自适应 为例,整理了下自适应的几种方法:

1. float浮动 && margin-left

    .outer{
      overflow: hidden;
      width: 100%;
      height: 100%;
    }
    /*清除浮动*/
    .outer::after{
      content: "";
      clear: both;
    }
    .sidebar{
      float: left;
      width: 200px;
      height: 100%;
      background: tomato;
    }
    .content{
      margin-left: 200px;
      height: 100%;
      background: seagreen;
    }

2. float && bfc

    .outer{
      overflow: hidden;
      width: 100%;
      height: 100%;
    }
    /*清除浮动*/
    .outer::after{
      content: "";
      height: 0;
      line-height: 0;
      display: block;
      visibility: hidden;
      clear: both;
    }
    .sidebar{
      float: left;
      width: 200px;
      height: 100%;
      background: tomato;
    }
    .content{
      overflow: hidden;
      height: 100%;
      background: seagreen;
    }

3. absolute 绝对定位 && margin-left

    .outer{
      position: relative;
      height: 100%;
    }
    .sidebar{
      position: absolute;
      top: 0;
      left: 0;
      width: 200px;
      height: 100%;
      background: tomato;
    }
    .content{
      margin-left: 200px;
      height: 100%;
      background: seagreen;
    }

4. inline-block && calc()

父元素需要设置font-size:0清除默认间距,子元素设置vertical-align:top使其顶部对齐, 记得在子元素中将font-size重新设置下。

.outer{
      font-size: 0;
      height: 100%;
    }
    .sidebar{
      display: inline-block;
      width: 200px;
      height: 100%;
      font-size: 14px;
      background: tomato;
    }
    .content{
      display: inline-block;
      vertical-align: top;
      width: calc(100% - 200px);
      height: 100%;
      font-size: 14px;
      background: seagreen;
    }

5. table-cell 表格布局 (张鑫旭写的方法)

   .outer{
      *zoom:1;
      height: 100%;
    }
    .outer:after{
      display:block;
      content:"";
      height:0;
      clear:both;
      visibility:hidden;
    }
    .sidebar{
      float:left;
      width: 200px;
      height: 100%;
      background: tomato;
    }
    .content{
      display:table-cell;
      *display:inline-block;
      width:2000px;
      *width:auto;
      height: 100%;
      background: seagreen;
    }

6. flex

   .outer{
      display: flex;
      height: 100%;
    }
    .sidebar{
      width: 200px;
      height: 100%;
      background: tomato;
    }
    .content{
      flex-grow: 1;
      height: 100%;
      background: seagreen;
    }

你可能感兴趣的:(宽度自适应的n种方法)