CSS 左中右三列布局左右固定宽度,固定位置,中间自适应的5种方式
如图:
1.float布局
左右分别float:left/right;中间撑开
<section class="layout float">
<style>
.layout {
margin-top: 10px;
}
.layout article div {
height: 100px;
}
.layout.float .left {
float: left;
width: 300px;
background: red;
}
.layout.float .center {
background: #0fff;
}
.layout.float .right {
float: right;
width: 300px;
background: yellow;
}
</style>
<article>
<div class="left"></div>
<div class="right"></div>
<div class="center">z这个是一个三部分左-中-右的布局根据float设置 第三方哈咖啡这里是最近刚好中间内容</div>
</article>
</section>
⚠️注意:这里要注意 center应该写在right后边,否则会把right挤到下一行,具体效果及原因参见 float元素先后顺序
2.position: absolute固定定位
左中右全部设置position:absolute;左边left:0;右边right:0;中间:left:300px;right:300px;
<section class="layout absolute">
<style>
.layout {
margin-top: 10px;
}
.layout article div {
height: 100px;
}
.absolute div {
position: absolute;
}
.absolute .left {
left: 0;
width: 300px;
background: red;
}
.absolute .center {
left: 300px;
right: 300px;
background: #00ffff;
}
.absolute .right {
right: 0;
width: 300px;
background: yellow;
}
</style>
<article>
<div class="left"></div>
<div class="center">z这个是一个三部分左-中-右的布局根据absolute设置 第三方哈咖啡这里是最近刚好中间内容</div>
<div class="right"></div>
</article>
</section>
3.flex弹性盒子布局
中间flex:1;自动填充剩余空间
<section class="layout flex">
<style>
.layout {
margin-top: 10px;
}
.layout article div {
height: 100px;
}
.flex article {
display: flex;
justify-content: center;
align-items: center;
}
.flex .left {
width: 300px;
background: red;
}
.flex .center {
flex: 1;
background: #0fff;
}
.flex .right {
width: 300px;
background: yellow;
}
</style>
<article>
<div class="left"></div>
<div class="center">z这是flex布局</div>
<div class="right"></div>
</article>
</section>
4.display:table;布局
<section class="layout table">
<style>
.layout {
margin-top: 10px;
}
.layout article div {
height: 100px;
}
.table article {
display: table;
width: 100%;
}
.table article>div {
display: table-cell;
}
.table .left {
width: 300px;
background: red;
}
.table .center {
background: #0ff;
}
.table .right {
width: 300px;
background: yellow;
}
</style>
<article>
<div class="left"></div>
<div class="center">这是table设置</div>
<div class="right">1</div>
</article>
</section>
5.display:grid; 网格布局
<section class="layout grid">
<style>
.layout {
margin-top: 10px;
}
.layout article div {
height: 100px;
}
.grid article {
display: grid;
width: 100%;
grid-template-rows: 100%;
grid-template-columns: 300px auto 300px;
}
.grid .left {
background: red;
}
.grid .center {
background: #0ff;
}
.grid .right {
background: yellow;
}
</style>
<article>
<div class="left"></div>
<div class="center">这是grid布局</div>
<div class="right"></div>
</article>
</section>