三栏布局在平时工作中经常遇到,现在我整理了下六种三栏布局的方式,以及优缺点
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>三栏布局</title>
</head>
<body>
<!-- 1.float + margin(浮动布局)
优点:快捷 简单 兼容性较好
缺点: 有局限性 脱离文档流 需要清除浮动等-->
<div class='parent'>
<div class='left'>left</div>
<div class='right'>right</div>
<div class='center'>center</div>
</div>
<style>
html,body,.parent{
padding: 0;
margin: 0;
overflow: hidden;
}
.left{
float:left;
height: 100%;
width:200px;
background:red
}
.center{
height: 100%;
margin: 0 200px;
background-color: yellow;
}
.right{
float:right;
height: 100%;
width:200px;
background-color: blue;
}
</style>
<!-- position绝对布局
优点:简单粗暴
缺点: 脱离文档流 高度未知会出现问题 可用性差 -->
重点:高度已知的时候可用,未知不可用
<div class="parent">
<div class="left">left1</div>
<div class="right">right1</div>
<div class="center">center1</div>
</div>
<style>
html,body,.parent{
padding: 0;
margin: 0;
overflow: hidden;
}
.left,.right{
position: absolute;
top: 0;
overflow: hidden;
width:200px;
}
.left{
left:0;
background-color: yellow;
}
.right{
right:0;
background-color: blue;
}
.center{
height: 100%;
background-color: red;
margin: 0 200px;
}
</style>
<!-- 3.flex(弹性盒子布局)
优点:比较完美 移动端首选
缺点: 不兼容 ie9 及以下-->
重点:高度已知未知都可用
<div class="parent">
<div class="left">left2</div>
<div class="center">center2</div>
<div class="right">right2</div>
</div>
<style>
body,html{
padding: 0;
margin: 0;
overflow: hidden;
}
.parent{
display: flex;
}
.left{
width:200px;
background: red;
}
.center{
flex:1;
background:yellow
}
.right{
width:200px;
background-color: green;
}
</style>
<!-- 4.table(表格布局) 优点:兼容性很好(ie8 及以上) 父元素高度会被子元素撑开(不担心高度塌陷)
缺点: seo 不友好 当其中一个单元格高度超出的时候,其他的单元格也是会跟着一起变高的-->
重点:高度已知未知都可用
<div class="parent">
<div class="left">left3</div>
<div class="center">center3</div>
<div class="right">right3</div>
</div>
<style>
body,html{
padding: 0;
margin: 0;
}
.parent{
display: table;
width: 100%;
}
.parent>div{
display: table-cell;
}
.left{
width:200px;
background-color: red
}
.center{
background-color: #FFFF00;
}
.right{
width: 200px;
background-color: aqua;
}
</style>
<!-- 5.Grid(网格布局)
优点:简单强大 解决二维布局问题
缺点: 不兼容 ie9 及以下-->
重点:高度已知的时候可用,未知不可用
<div class="parent">
<div class="left">left4</div>
<div class="center">center4</div>
<div class="right">right4</div>
</div>
<style>
body,html{
padding: 0;
margin: 0;
}
.parent{
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 200px auto 200px;
}
.left{
background-color: red;
}
.center{
background-color: aqua;
}
.right{
background-color: #FFFF00;
}
</style>
<!-- 6float实现 优点兼容性好 缺点脱离文档流,DOM节点顺序错误 -->
重点:高度已知的时候可用,未知不可用
<div>6 float实现三栏布局</div>
<div class="float-div">
<div class="float-left"></div>
<div class="float-right"></div>
<div class="float-center"></div>
</div>
<style>
.float-div .float-left {
float: left;
width: 300px;
background: green;
height: 200px;
}
.float-right {
width: 300px;
float: right;
background: red;
height: 200px;
}
.float-center {
background: yellow;
height: 200px;
}
</style>
</body>
</html>