左右固定,中间自适应的三栏式布局五种写法
三栏式布局是工作中常用的布局方式,三栏式布局有多种写法,作为前端开发,对布局的了解也是一项基本功,
下面是整理的五种三栏式布局的基本写法
公共样式
//清除默认样式 html *{padding: 0;margin:0;} //layout公共样式 .layout{margin-top:20px;} .layout div{min-height: 100px;}
1. 浮动布局(浮动会是文档脱离文档流,需要清浮动)
<section class="layout float"> <style> .layout.float .left{float: left;width: 300px;background: red;} .layout.float .right{float: right;width: 300px;background: blue;} .layout.float .center{background: yellow;} </style> <article class="con"> <div class="left"></div> <div class="right"></div> <div class="center"> <h1>浮动布局</h1> 这是中间部分 </div> </article> </section>
2. 绝对定位布局(绝对定位也会脱离文档流)
<section class="layout absolute"> <style> .layout.absolute .con>div{position: absolute;} .layout.absolute .left{left:0;width: 300px;background: red;} .layout.absolute .right{right:0;width: 300px;background: blue;} .layout.absolute .center{background: yellow;left: 300px;right: 300px;} </style> <article class="con"> <div class="left"></div> <div class="center"> <h1>绝对定位布局</h1> 这是中间部分 </div> <div class="right"></div> </article> </section>
3. flex布局(css3的新语法,pc兼容性问题,常用于移动端,中间被内容撑开高度时,左右两边的高度也能同中间保持一致)
<section class="layout flexbox"> <style> .layout.flexbox{margin-top: 140px;} .layout.flexbox .con{display: flex;} .layout.flexbox .left{width: 300px;background: red;} .layout.flexbox .right{width: 300px;background: blue;} .layout.flexbox .center{background: yellow;flex: 1;} </style> <article class="con"> <div class="left"></div> <div class="center"> <h1>flex布局</h1> 这是中间部分 </div> <div class="right"></div> </article> </section>
4. 表格布局(中间被内容撑开高度时,左右两边的高度也能同中间保持一致)
<section class="layout table"> <style> .layout.table .con{width: 100%;display: table;height: 100px;} .layout.table .con>div{display: table-cell;} .layout.table .left{width: 300px;background: red;} .layout.table .right{width: 300px;background: blue;} .layout.table .center{background: yellow;} </style> <article class="con"> <div class="left"></div> <div class="center"> <h1>表格布局</h1> 这是中间部分 </div> <div class="right"></div> </article> </section>
5.网格布局(新语法,代码量少)
<section class="layout grid"> <style> .layout.grid .con{display: grid;width: 100%;grid-template-rows: 100px;grid-template-columns: 300px auto 300px;} .layout.grid .left{background: red;} .layout.grid .right{background: blue;} .layout.grid .center{background: yellow;} </style> <article class="con"> <div class="left"></div> <div class="center"> <h1>网格布局</h1> 这是中间部分 </div> <div class="right"></div> </article> </section>