前面的話
前面已經介紹過css 兩列布局中單列定寬單列自適應布局的6種思路的兩列布局,而兩列自適應布局是指一列由內容撐開,另一列撐滿剩余寬度的布局方式。本文將從float、table、flex和grid來介紹兩列自適應布局的4種思路
float
【思路一】float
在單列定寬單列自適應的兩列布局中,經常用float和負margin配合實現布局效果。但由於margin取值只能是固定值,所以在兩列都是自適應的布局中就不再適用。而float和overflow配合可實現兩列自適應效果。使用overflow屬性來觸發bfc,來阻止浮動造成的文字環繞效果。由於設置overflow:hidden並不會觸發IE6-瀏覽器的haslayout屬性,所以需要設置zoom:1來兼容IE6-瀏覽器
<style> p{margin: 0;} .parent{overflow: hidden;zoom: 1;} .left{float: left;margin-right: 20px;} .right{overflow: hidden;zoom: 1;} </style>
<div class="parent" style=""> <div class="left" style=""> <p>left</p> </div> <div class="right" style=""> <p>right</p> <p>right</p> </div> </div>
table
【思路二】table
若table元素不設置table-layout:fixed,則寬度由內容撐開。在某個table-cell元素的外層嵌套一層div,並設置足夠小的寬度如width:0.1%
<style> p{margin: 0;} .parent{display:table;width:100%;} .leftWrap{display:table-cell;width:0.1%;} .left{margin-right: 20px;} .right{display:table-cell;} </style>
<div class="parent" style=""> <div class="leftWrap" style=""> <div class="left" style=""> <p>left</p> </div> </div> <div class="right" style=""> <p>right</p> <p>right</p> </div> </div>
flex
【思路三】flex
flex彈性盒模型是非常強大的布局方式。基本上,一般的布局方式都可以實現
[注意]IE9-不支持
<style> p{margin: 0;} .parent{display:flex;} .right{margin-left:20px; flex:1;} </style>
<div class="parent" style=""> <div class="left" style=""> <p>left</p> </div> <div class="right" style=""> <p>right</p> <p>right</p> </div> </div>
grid
【思路四】grid
[注意]IE10-瀏覽器不支持
<style> p{margin: 0;} .parent{display:grid;grid-template-columns:auto 1fr;grid-gap:20px} </style>
<div class="parent" style=""> <div class="left" style=""> <p>left</p> </div> <div class="right" style=""> <p>right</p> <p>right</p> </div> </div>
轉載:http://www.cnblogs.com/xiaohuochai/p/5454232.html