题目:假设高度已知,三栏布局,其中左栏和右栏宽度为200px,中间自适应
全局样式
html *{
padding: 0;
margin: 0;
}
.layout{
margin-top: 20px;
}
.layout article div{
min-height: 100px;
}
1、浮动布局
<section class="layout float">
<style media="screen">
.layout.float .left{
float: left;
width: 200px;
background: red;
}
.layout.float .right{
float: right;
width: 200px;
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>1、这是三栏布局中间部分</p>
<p>2、这是三栏布局中间部分</p>
</div>
</article>
</section>
2、绝对定位
<section class="layout absolute">
<style media="screen">
.layout.absolute .left-right-center>div{
position: absolute;
}
.layout.absolute .left{
left: 0;
width: 200px;
background: red;
}
.layout.absolute .center{
left: 200px;
right: 200px;
background: yellow;
}
.layout.absolute .right{
right: 0;
width: 200px;
background: blue;
}
</style>
<article class="left-right-center">
<div class="left"></div>
<div class="center">
<h1>绝对定位解决方案</h1>
<p>1、这是三栏布局中间部分</p>
<p>2、这是三栏布局中间部分</p>
</div>
<div class="right"></div>
</article>
</section>
3、flexbox布局
<section class="layout flexbox">
<style media="screen">
.layout.flexbox{
margin-top: 150px;
}
.layout.flexbox .left-right-center{
display: flex;
}
.layout.flexbox .left{
width: 200px;
background: red;
}
.layout.flexbox .center{
flex: 1;
background: yellow;
}
.layout.flexbox .right{
width: 200px;
background: blue;
}
</style>
<article class="left-right-center">
<div class="left"></div>
<div class="center">
<h1>flex解决方案</h1>
<p>1、这是三栏布局中间部分</p>
<p>2、这是三栏布局中间部分</p>
</div>
<div class="right"></div>
</article>
</section>
4、表格布局
<section class="layout table">
<style media="screen">
.layout.table .left-right-center{
display: table;
width: 100%;
height: 100px;
}
.layout.table .left-right-center>div{
display: table-cell;
}
.layout.table .left{
width: 200px;
background: red;
}
.layout.table .center{
background: yellow;
}
.layout.table .right{
width: 200px;
background: blue;
}
</style>
<article class="left-right-center">
<div class="left"></div>
<div class="center">
<h1>表格布局解决方案</h1>
<p>1、这是三栏布局中间部分</p>
<p>2、这是三栏布局中间部分</p>
</div>
<div class="right"></div>
</article>
</section>
5、网格布局
<section class="layout grid">
<style media="screen">
.layout.grid .left-right-center{
display: grid;
width: 100%;
height: 100px;
grid-template-rows: 100px;
grid-template-columns:200px auto 200px;
}
.layout.grid .left{
background: red;
}
.layout.grid .center{
background: yellow;
}
.layout.grid .right{
background: blue;
}
</style>
<article class="left-right-center">
<div class="left"></div>
<div class="center">
<h1>网格布局解决方案</h1>
<p>1、这是三栏布局中间部分</p>
<p>2、这是三栏布局中间部分</p>
</div>
<div class="right"></div>
</article>
</section>
总结:
1、各方案优缺点
float:需要清除浮动,但是兼容性好;
绝对定位:快捷,已理解,但是绝对定位脱离了文档流,可用性差;
flexbox:有兼容性,其他的都挺好的;
表格布局:兼容性好;
网格布局:有兼容性
2、拓展
如果高度未知,flexbox和表格布局仍然可以使用。