前言:本文介绍五种常见的三列布局,主要是两侧定宽,中间自适应,其他情况大同小异。
方式一:float
HTML代码:
<div class="layout-float">
<div class="left">左边</div> <div class="right">右边</div>
<div class="center">中间</div>
</div>
注:center要放最后。center这个元素是块级元素,占据一行,如果center放中间,right元素会在下一行向右浮动
CSS代码:
<style> .left { float: left; width: 300px; background-color: blue; } .right { float: right; width: 300px; background-color: blue; } .center { background-color: red; }</style>
方式二:table布局,非HTML中<table>标签
HTML代码:
<div class="layout-table"> <div class="left"></div> <div class="center">这是中间</div> <div class="right"></div></div>
CSS代码:
<style> .layout-table{ width: 100%; display: table; height: 100px; } .layout-table div { display: table-cell; } .left { width: 300px; background-color: blue; } .right { width: 300px; background-color: red; } .center { background-color: blue; }</style>
方式三:flex布局
HTML代码:
<div class="layout-flexbox"> <div class="left"></div> <div class="center">这是中间</div> <div class="right"></div></div>
CSS代码:
<style> .layout-flexbox{ display: flex; } .left { width: 300px; background-color: blue; } .center { flex: 1; background-color: green; } .right { width: 300px; background-color: blue; }</style>
方式四:grid布局
HTML代码:
<div class="layout-grid"> <div class="left"></div> <div class="center">这是中间</div> <div class="right"></div></div>
CSS代码:
<style> .layout-grid{ display: grid; width:100%; grid-template-rows:100px; grid-template-colums:300px auto 300px; } .left { background-color: blue; } .center { background-color: green; } .right { background-color: blue; }</style>
方式五:绝对布局
HTML代码:
<div class="layout-absolute"> <div class="left"></div> <div class="center">这是中间</div> <div class="right"></div></div>
CSS代码:
<style> .layout-absolute div{ position: absolute; } .left { left:0; width:300px; background-color: blue; } .center { left:300px; right:300px; background-color: green; } .right { width:300px; right:0; background-color: blue; }</style>
五种方法的优缺点:
float:兼容性较好,一般需要清除浮动
table:兼容性较好,SEO不太友好
grid:新技术,对旧浏览器兼容不太好,代码简洁
absolute:方便易用,脱离文档流,可使用性较差
flex:没什么明显缺点,且移动端友好
作者:dzwonline
原文链接:https://www.cnblogs.com/dzwonline/p/9163019.html