两列或三列自适应布局方案
1、两列布局
左边固定宽度,右边自适应
1.1、左边float,右边margin-left,为防止包括元素塌陷,使用overflow:hidden,形成BFC
<style> .box{ overflow: hidden; // BFC } .left { float: left; width: 200px; background-color: gray; height: 400px; } .right { margin-left: 210px; background-color: lightgray; height: 200px; } </style> <div class="box"> <div class="left"></div> <div class="right"></div> </div>
1.2、使用flex布局
<style> .box{ display: flex; } .left { width: 100px; } .right { flex: 1; } </style> <div class="box"> <div class="left"> </div> <div class="right"> </div> </div>
flex布局代码样式比较简洁,但是flex之后,子元素会出现等高现象,处理方式是align-items:flex-start
2、三列自动布局
2.1、左右使用float,中间使用margin,防止父元素塌陷,形成BFC
2.2、左右使用absolute,中间使用margin
2.3、左右使用float+margin(负值),需要调整html位置
<style> .left, .right, .main { height: 200px; line-height: 200px; text-align: center; } .main-wrapper { float: left; width: 100%; } .main { margin: 0 110px; background: black; color: white; } .left, .right { float: left; width: 100px; margin-left: -100%; background: green; } .right { margin-left: -100px; } </style> <div class="main-wrapper"> <div class="main"> </div> </div> <div class="left"> </div> <div class="right"> </div>
2.4、使用table布局,子元素都是table-cell
<style> .container { height: 200px; line-height: 200px; text-align: center; display: table; table-layout: fixed; width: 100%; } .left, .right, .main { display: table-cell; } .left, .right { width: 100px; background: green; } .main { background: black; color: white; width: 100%; } </style> <div class="container"> <div class="left"> </div> <div class="main"> </div> <div class="right"> </div> </div>
2.5、弹性布局flex
<style> .main-wrapper { height: 200px; display: flex; width: 100%; } .main { flex: 1; margin: 0 10px; background: black; color: white; } .left, .right { width: 100px; background: green; } </style> <div class="main-wrapper"> <div class="left"> </div> <div class="main"> </div> <div class="right"> </div> </div>
2.6、使用网格布局grid
<style> .main-wrapper { height: 200px; display: grid; grid-template-columns: 100px auto 100px; grid-gap: 5px; width: 100%; } .main { background: black; color: white; } .left, .right { background: green; } </style> <div class="main-wrapper"> <div class="left"> </div> <div class="main"> </div> <div class="right"> </div>