前提:高度已知,左右宽300px,中间自适应的三栏布局。
公共样式:
<style>
* {padding:0;margin:0}
.main div{min-height:100px;}
</style>
1、浮动布局
<style>
.left{
width:300px;
background:red;
float:left;
}
.center{
background:yellow;
}
.right{
width:300px;
background:blue;
float:right;
}
.clear{clear:both}
</style>
<body>
<div class="main">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
<div class="clear"></div>
</div>
</body>
注意,三个div盒子的顺序不能改变,不然无法实现三栏布局,.center盒子要放到最后。还有一个问题就是,如果center盒子的内容超过了,在超过的高度后,内容会呈现新水平平铺状态,而不是保持原先的宽度,会导致.center盒子呈倒T字形。浮动布局具有局限性,需要清除浮动。
2、绝对定位布局
.left{
width:300px;
background:red;
position:absolute;
left:0;
}
.center{
position:absolute;
left:300px;
right:300px;
background:yellow;
}
.right{
postion:absolute:
right:0;
background:blue
}
<div class="main">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
绝对定位脱离了文档流,有效性和可用性比较差。自己的高度超了以后不会影响其他两个的高度。
3、flex布局
.main{
display:flex;
}
.left{
width:300px;
background:red;
}
.center{
background:yellow;
flex:1
}
.right{
width:300px;
background:blue;
}
<div class="main">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
flex布局算是比较完美的一种,弥补了浮动布局和绝对定位布局的不足,弹性布局的唯一缺陷是不兼容IE8及以下的浏览器。
注意:flex布局三个盒子的高度都是一样高的,高度为最高的那个盒子的高度。
4、表格布局
* {padding:0;margin:0}
.main{
width:100%;
min-height:100px;
display:table;
}
.main div{
display:table-cell;
}
.left{
width:300px;
background:red;
}
.center{
background:yellow;
}
.right{
width:300px;
background:blue;
}
<div class="main">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
注意:容器要设定宽度,否则无法实现三栏布局,中间的显示不出来。表格布局等高,一个单元格超出,其他的单元格也会跟着变高。
5、网格布局
* {padding:0;margin:0}
.main{
width:100%;
display:grid;
mim-height:100px;
/*grid-template-rows: 100px;*/
grid-template-columns: 300px auto 300px;
}
.left{
background:red;
}
.center{
background:yellow;
}
.right{
width:300px;
background:blue;
}
<div class="main">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
网格布局也是新出的一种布局方式,同等高。