布局解决方案之多列布局
1、定宽与自适应布局
方案1:float + margin
CSS代码:
1 .left{ 2 float: left; 3 width: 100px; 4 background-color: red; 5 } 6 .right{ 7 background-color: green; 8 margin-left: 120px; 9 }
HTML代码:
1 <div class="parent"> 2 <div class="left"> 3 <p>left</p> 4 </div> 5 <div class="right"> 6 <p>right</p> 7 <p>right</p> 8 </div> 9 </div>
方案2:float + margin + (fix)
CSS代码:
1 .left{ 2 float: left; 3 width: 100px; 4 position:relative; 5 } 6 .right-fix{ 7 float: right; 8 width: 100%; 9 margin-left: -100px; 10 } 11 .right{ 12 background-color: green; 13 margin-left: 120px; 14 }
HTML代码:
1 <div class="parent"> 2 <div class="left"> 3 <p>left</p> 4 </div> 5 <div class="right-fix"> 6 <div class="right"> 7 <p>right</p> 8 <p>right</p> 9 </div> 10 </div> 11 </div>
方案3:float + overflow
1 .left{ 2 float: left; 3 width: 100px; 4 margin-right: 20px; 5 } 6 .right{ 7 background-color: green; 8 overflow: hidden; 9 }
HTMl代码:
<div class="parent"> <div class="left"> <p>left</p> </div> <div class="right"> <p>right</p> <p>right</p> </div> </div>
方案4:flex
1 .parent{ 2 display: flex; 3 } 4 .left{ 5 width: 100px; 6 margin-right: 20px; 7 } 8 .right{ 9 flex:1; 10 }
HTML代码:
1 <div class="parent"> 2 <div class="left"> 3 <p>left</p> 4 </div> 5 <div class="right"> 6 <p>right</p> 7 <p>right</p> 8 </div> 9 </div>
由于flex性能问题,所以flex多用于小范围布局。
2、不定宽与自适应布局
方案1:利用定宽与自适应布局方案的方案3来实现,参照上文。
方案2:利用定宽与自适应布局方案的方案4来实现,参照上文。
3、等分布局(等宽+等间距)
方案1:float(以4列为例)
CSS代码
1 .parent{ 2 margin-left: -20px; 3 } 4 .column{ 5 float: left; 6 width: 25%; 7 padding-left: 20px; 8 box-sizing: border-box; 9 background-color: red; 10 }
HTML代码:
1 <div class="parent"> 2 <div class="column"><p>1</p></div> 3 <div class="column"><p>2</p></div> 4 <div class="column"><p>3</p></div> 5 <div class="column"><p>4</p></div> 6 </div>
方案2:flex
CSS代码:
1 .parent{ 2 display: flex; 3 } 4 .column{ 5 flex:1; 6 } 7 .column+.column{ 8 margin-left: 20px; 9 }
HTMl代码:
1 <div class="parent"> 2 <div class="column"><p>1</p></div> 3 <div class="column"><p>2</p></div> 4 <div class="column"><p>3</p></div> 5 <div class="column"><p>4</p></div> 6 </div>
4、等高布局
方案1:利用定宽与自适应布局的方案4来实现,参照上文。
方案2:float
CSS代码:
1 .parent{ 2 overflow: hidden; 3 } 4 .left,.right{ 5 padding-bottom: 9999px; 6 margin-bottom: -9999px; 7 } 8 .left{ 9 float: left; 10 width: 100px; 11 margin-right: 20px; 12 background-color: red; 13 } 14 .right{ 15 overflow: hidden; 16 background-color: green; 17 }
HTML代码:
1 <div class="parent"> 2 <div class="left"> 3 <p>left</p> 4 </div> 5 <div class="right"> 6 <p>right</p> 7 <p>right</p> 8 </div> 9 </div>