探讨“左右定宽,中间自适应”的几种布局方式
一、实现“左右定宽,中间自适应”三栏效果的5种方式
基本 DOM 结构:
<article class="container"> <div class="left">this is left</div> <div class="center">this is center this is center this is center</div> <div class="right">this is right</div> </article>
1、使用浮动
div { min-height: 400px; } .left { width: 200px; background: pink; float: left; } .center { background: lightgreen; } .right { width: 200px; background: lightblue; float: right; }
左栏和右栏分别设置 float 为 left 和 right
注意:使用此方式 HTML 中三栏的顺序为:左-右-中
<article class="container"> <div class="left">this is left</div> <div class="right">this is right</div> <div class="center">this is center this is center this is center</div> </article>
2、使用绝对定位
div { min-height: 400px; } .left { width: 200px; background: pink; position: absolute; left: 0; } .center { background: lightgreen; position: absolute; left: 200px; right: 200px; } .right { width: 200px; background: lightblue; position: absolute; right: 0; }
对三栏设 position 为 absolute,左栏和右栏分别设 left 和 right 的值为 0,中间栏设置 left 和 right 的值为左栏和右栏的宽度
此方式 HTML 中三栏的顺序不影响最终效果
3、使用弹性布局
div { min-height: 400px; } article { display: flex; } .left { width: 200px; background: pink; } .center { background: lightgreen; flex: 1; } .right { width: 200px; background: lightblue; }
为三栏的父元素设置 display 为 flex,并在中间栏设置 flex 的值为 1
注意:使用此方式 HTML 中三栏的顺序为:左-中-右
<article class="container"> <div class="left">this is left</div> <div class="center">this is center this is center this is center</div> <div class="right">this is right</div> </article>
4、使用表格布局
article { width: 100%; height: 400px; display: table; } .left { width: 200px; background: pink; display: table-cell; } .center { background: lightgreen; display: table-cell; } .right { width: 200px; background: lightblue; display: table-cell; }
对三栏的父元素设置 display 为 table,同时设置宽和高,并对三栏设 display 为 table-cell
注意:使用此方式 HTML 中三栏的顺序为:左-中-右
<article class="container"> <div class="left">this is left</div> <div class="center">this is center this is center this is center</div> <div class="right">this is right</div> </article>
5、使用网格布局
article { width: 100%; display: grid; grid-template-rows: 400px; grid-template-columns: 200px auto 200px; } .left { background: pink; } .center { background: lightgreen; } .right { background: lightblue; }
对三栏的父元素设置 display 为 grid,同时设置宽度、grid-template-rows 和 grid-template-columns
注意:使用此方式 HTML 中三栏的顺序为:左-中-右
二、如果增加任一栏的高度,哪个能正常拉伸?效果如下:
上述五种方式中,只有 flex 和 table 两种方式能在增加高度时正常撑开