左右各300px,中间自适应,高度固定。
1. 浮动布局
<section class="layout float">
<style>
.layout.float .left{
float: left;
width: 300px;
background: red;
}
.layout.float .right{
float: right;
width: 300px;
background: blue;
}
.layout.float .center{
background: yellow;
}
</style>
<article class="left-right-center">
<div class="left"></div>
<div class="right"></div>
<div class="center">
<h1>浮动解决方案</h1>
<p>这是三栏布局中间部分</p>
</div>
</article>
</section>
- 缺点:需要清除浮动;
- 优点:兼容性好。
2. 绝对定位布局
<section class="layout absolute">
<style>
.layout.absolute .left-center-right > div{
position: absolute;
}
.layout.absolute .left {
left: 0;
width: 300px;
background: red;
}
.layout.absolute .center {
left: 300px;
right: 300px;
background: yellow;
}
.layout.absolute .right {
right: 0;
width: 300px;
background: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
<h1>绝对定位解决方案</h1>
<p>这是三栏布局绝对定位中间部分</p>
</div>
<div class="right"></div>
</article>
</section>
- 缺点:布局已经脱离文档流了,所有的子元素也必须脱离文档流。
- 优点:快捷,配合js使用。
3. flex布局
<section class="layout flexbox fix">
<style>
.layout.flexbox .left-center-right{
display: flex;
}
.layout.flexbox .left{
width: 300px;
background: red;
}
.layout.flexbox .center{
flex: 1;
background: yellow;
}
.layout.flexbox .right{
width: 300px;
background: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
<h1>flexbox解决方案</h1>
<p>这是三栏布局flexbox中间部分</p>
</div>
<div class="right"></div>
</article>
</section>
- 缺点:flex是css3中提出的,兼容性不太好。
- 优点:为了解决上述两种布局的问题提出的,而且特别适用于移动端。
4. 表格布局
<section class="layout table">
<style>
.layout.table .left-center-right{
display: table;
width: 100%;
height: 100px;
}
.layout.table .left-center-right> div {
display: table-cell;
}
.layout.table .left{
width: 300px;
background: red;
}
.layout.table .center{
background: yellow;
}
.layout.table .right{
width: 300px;
background: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
<h1>table布局解决方案</h1>
<p>这是三栏布局table布局中间部分</p>
</div>
<div class="right"></div>
</article>
</section>
- 缺点:除了历史上的诟病以外,当其中某一个单元格的高度变化的时候,同一行的其他单元格也会变化。
- 优点:在很多场景是非常适用的,兼容性特别好,对于flex布局不兼容的浏览器,比如ie8,如果想实现同样效果,可以使用表格布局。
5. 网格布局
<section class="layout grid">
<style media="screen">
.layout.grid .left-center-right{
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.layout.grid .left{
background: red;
}
.layout.grid .center {
background: yellow;
}
.layout.grid .right {
background: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
<h1>网格布局解决方案</h1>
<p>这是三栏布局网格布局中间部分</p>
</div>
<div class="right"></div>
</article>
</section>
当高度未知时,只有flex布局和表格布局还适用,其高度会随着内容的变化自适应,其他都会出问题。例如第一个浮动布局中,当内容超出之后,超出的部分会跑到三栏布局下方,而且是靠最左边对齐(跑到原布局的左栏下方),解决方案是创建BFC。