css实现常用的两栏三栏布局
1、两栏
<div class="wrapper"> <div class="half left">left box
<p>自适应</p>
</div> <div class="half right">right box 固定</div> </div>
1.1、左侧宽度固定,右侧自适应
方式一、float+margin
.wrapper{ width: 100%; overflow: auto; //清浮动 } .left{ float: left; width: 200px; background-color: #5cb85c; } .right{ margin-left: 230px; background-color: #66afe9; }
方式二、float+overflow
.wrapper{ width: 100%; overflow: auto; //清浮动,或overflow:hidden } .left{ float: left; width: 200px; margin-left: 30px; background-color: #5cb85c; } .right{ overflow: hidden; //或overflow: auto background-color: #66afe9; }
方式三、float+position
.wrapper{ position: relative; width: 100%; overflow: auto; //清浮动,或overflow:hidden } .left{ float: left; width: 200px; background-color: #5cb85c; } .right{ position: absolute; left: 230px; right: 0; background-color: #66afe9; }
方式四、flex
.wrapper{ display: flex; flex-direction: row; width: 100%; } .left{ flex: 0 0 auto; width: 200px; margin-right: 30px; background-color: #5cb85c; } .right{ flex: 1; background-color: #66afe9; }
2、三栏
两边固定中间自适应
方式一、float+margin
<div class="wrapper">
<div class="left">left box
<p>固定</p>
</div>
<div class="right">right box
<h4>ssss</h4>
<h5>ddddd</h5>
</div>
<div class="middle">中间自适应</div>
</div>
//css .wrapper{ width: 100%; overflow: auto; } .wrapper .left{ float: left; width: 200px; background-color: #5cb85c; } .wrapper .right{ float: right; width: 100px; background-color: #66afe9; } .wrapper .middle{ margin: 0 110px 0 230px; background-color: #A3AEFF; }
方式二、position+margin (这种方式的父元素高度取决于中间部分的高度,当两侧高度大于中间高度时,则出现高度塌陷,除非指定父元素的高度,当两侧高度小于中间部分时,可以使用。)
.wrapper{ position: relative; width: 100%; } .wrapper .left{ position: absolute; left: 0; width: 200px; background-color: #5cb85c; } .wrapper .right{ position: absolute; right: 0; width: 100px; background-color: #66afe9; } .wrapper .middle{ margin: 0 110px 0 230px; background-color: #A3AEFF; }
方式三、flex
<div class="wrapper"> <div class="left">left box <p>固定</p> </div> <div class="middle">中间自适应</div> <div class="right">right box <h4>ssss</h4> <h5>ddddd</h5> </div> </div> .wrapper{ display: flex; flex-direction: row; width: 100%; .left{ width: 200px; background-color: #5cb85c; } .right{ width: 100px; background-color: #66afe9; } .middle{ flex: 1; margin: 0 10px 0 30px; background-color: #A3AEFF; } }