css的两栏布局是比较经典的布局之一,一般是左(右)边定宽,右(左)边自适应。
实现的方式也比较多,今天主要介绍3种。
1.浮动方法,使第一个div浮动起来脱离文档流,下面的div自动向上
<body> <div class="left">左边</div> <div class="right">右边</div>
</body>
.left { width: 200px; height: 400px; background: yellow; float: left; } .right{ height: 400px; background: #0000FF; }
2.绝对定位法
此方法的原理是将左侧的div设置为position:absolute,右侧默认宽度,并将margin-left设置为和左侧div一样宽(如果要留间隙,可以大于左侧div宽度)
<body> <div class="left">左边</div> <div class="right">右边</div> </body>
.left { width: 200px; height: 400px; background: yellow; position: absolute; } .right { height: 400px; background: #ccc; margin-left: 200px; }
3.弹性盒。display:flex; 设置为弹性盒子,其子元素可以通过设置flex的数值来控制所占空间比例
<body> <div class="left">左边</div> <div class="right">右边</div> </body>
<style type="text/css"> body{ display: flex; } .left { width: 200px; height: 400px; background: yellow; } .right { height: 400px; background: #ccc; flex: 1; } </style>
三栏布局
三列自适应布局指的是两边定宽,中间宽度自适应
1.绝对定位法
原理是将两边absolute定位,因为绝对定位使其脱离文档流,后面的center会自然流动到上面,然后使用margin属性,留出左右元素的宽度,使中间的元素自适应。
<body> <div class="left">左边</div> <div class="center">中间</div> <div class="right">右边</div> </body>
<style type="text/css"> *{ margin: 0; padding: 0; } .left{ position: absolute; height: 400px; width: 400px; left: 0; top: 0; background: yellow; } .center{ height: 400px; background: blueviolet; } .right{ position: absolute; top: 0px; right: 0px; height: 400px; width: 400px; background: yellowgreen; } </style>
2.浮动定位
自身浮动定位的原理是使用float:left和float:right,float使左右两个元素脱离文档流,中间元素正常在文档流中。使用margin指定左右外边距对其进行定位。
<body> <div class="left">左边</div> <div class="right">右边</div> <div class="center">中间</div> </body>
<style type="text/css"> *{ margin: 0; padding: 0; } .left{ width: 300px; height: 300px; background: #DEB887; float: left; } .center{ height: 300px; background: #008000; margin: 0 310px; } .right{ width: 300px; height: 300px; background: #DEB887; float: right; } </style>
三个元素的顺序,center一定要放在嘴和,center占据文档流位置,所以一定要放到最后,左右两个元素位置没有关系,当浏览器窗口很小的时候,右边元素会被挤到下一行
3.flex布局法
目测这应该是未来主流的布局方式
用一个box包裹三栏,设置容器display:flex,左右栏固定宽度300px,中间栏设置flex:1,这里的1表示宽度比例,具体数值取决于其他盒子的flex值。由于这里其他盒子宽度固定,所以中间栏会自动填充。
<body> <div id="box"> <div class="left">左边</div> <div class="center">中间</div> <div class="right">右边</div> </div> </body>
<style type="text/css"> *{ margin: 0; padding: 0; } #box{ display: flex; height: 300px; } .left{ width: 300px; height: 300px; background: #DEB887; } .center{ height: 300px; background: #008000; flex: 1; } .right{ width: 300px; height: 300px; background: #DEB887; } </style>
本文没有配图,读者可自行尝试