左右寬度固定中間自適應html佈局解決方案

a.使用浮動佈局
html結構以下html

<div class="box">
    <div class="left">left</div>
    <div class="right">right</div>
    <div class="center">center</div>
</div>   
//此處注意要先渲染左、右浮動的元素纔到中間的元素。元素浮動後剩餘兄弟塊級元素會佔滿父元素的寬度
<style>
   .box{
        height:200px;
    }    
    .left{
        float:left;
        width:300px;
    }
    .right{
        float:right;
        width:300px;
    }
</style>

b.使用固定定位
html結構以下瀏覽器

<div class="box">
    <div class="left">left</div>
    <div class="right">right</div>
     <div class="center">center</div>
</div> 
//和浮動佈局同理,先渲染左右元素,使其定位在父元素的左右兩端,剩餘的中間元素佔滿父元素剩餘寬度。
<style>
    .box{
        position: relative;
      }
      .left{
        position: absolute;
        width: 100px;
        left: 0;
      }
      .right{
        width:100px;
        position: absolute;
        right: 0;
      }
      .center{
        margin: 0 100px;
        background: red;
      }
</style>

c.表格佈局
將父元素display:table,子元素display:table-cell,會將它變爲行內塊。
這種佈局方式的優勢是兼容性好。佈局

<div class="box">
  <div class="left">
    left
  </div>
  <div class="center">
    center
  </div>
  <div class="right">
    right
  </div>
</div>
<style>
    .box{
        display: table;
        width: 100%;
      }
      .left{
        display: table-cell;
        width: 100px;
        left: 0;
      }
      .right{
        width:100px;
        display: table-cell;
      }
      .center{
        width: 100%;
        background: red;
      }
</style>

d.彈性佈局
父元素display:flex子元素會所有並列在一排。
子元素中flex:n的寬度會將父元素的寬度/n
如flex:1,寬度就等於父元素高度。
彈性佈局的缺點是兼容性不高,目前IE瀏覽器沒法使用彈性佈局flex

<div class="box">
  <div class="left">
    left
  </div>
  <div class="center">
    center
  </div>
  <div class="right">
    right
  </div>
</div>
<style>
    .box{
        display: flex;
        width: 100%;
      }
      .left{
      
        width: 100px;
        left: 0;
      }
      .right{
        width:100px;
      }
      .center{
        flex:1;
      }
</style>

e.網格佈局
父元素display:grid;
grid-templatecolumns:100px auto 100px;
依次爲第一個子元素寬100px 第二個自適應 第三個100px;
網格佈局的優勢是極爲簡便,直接經過父元素樣式決定,缺點是兼容性不高。code

<div class="box">
  <div class="left">
    left
  </div>
  <div class="center">
    center
  </div>
  <div class="right">
    right
  </div>
</div>
<style>
  .box{
        display: grid;
        grid-template-columns: 100px auto 100px;
        width: 100%;
      }
</style>
相關文章
相關標籤/搜索