007-实现三栏布局中间自适应
前言
实现三栏布局的方式如下:
- 两边使用 float,中间使用 margin
- 两边使用 absolute,中间使用 margin
- display: table
- flex
- grid
两边使用 float,中间使用 margin
实现方式如下:
<div class="wrap clearfix">
<div class="left">left</div>
<div class="right">right</div>
<div class="center">center</div>
</div>
/* 清除浮动 */
.clearfix {
zoom: 1;
&::after {
display: block;
height: 0;
clear: both;
visibility: hidden;
content: '';
}
}
/* 清除浮动 */
.wrap {
height: 300px;
background-color: #eee;
.left {
float: left;
width: 200px;
height: 300px;
background-color: aqua;
}
.right {
float: right;
width: 200px;
height: 300px;
background-color: bisque;
}
.center {
height: 300px;
margin: 0 200px;
background-color: blueviolet;
}
}
注意
将 .center
放在 html 结构末尾,不然会呈现在 .right
的下方
两边使用 absolute,中间使用 margin
实现方式如下:
<div class="wrap">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
</div>
.wrap {
position: relative;
height: 300px;
background-color: #eee;
.left {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 300px;
background-color: aqua;
}
.right {
position: absolute;
top: 0;
right: 0;
width: 200px;
height: 300px;
background-color: bisque;
}
.center {
height: 300px;
margin: 0 200px;
background-color: blueviolet;
}
}
display: table 实现
实现方式如下:
<div class="wrap">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
</div>
.wrap {
display: table;
width: 100%;
height: 200px;
table-layout: fixed;
.left {
display: table-cell;
width: 200px;
background-color: aqua;
}
.right {
display: table-cell;
width: 200px;
background-color: bisque;
}
.center {
display: table-cell;
width: 100%;
background-color: blueviolet;
}
}
通过 display: table
设置为表格,设置 table-layout: fixed
表示列宽自身宽度决定,而不是自动计算。
flex 实现
实现方式如下:
<div class="wrap">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
</div>
.wrap {
display: flex;
justify-content: space-between;
.left {
width: 200px;
height: 300px;
background-color: aqua;
}
.right {
width: 200px;
height: 300px;
background-color: bisque;
}
.center {
width: 100%;
height: 300px;
margin: 0 30px;
background-color: blueviolet;
}
}
grid 实现
实现方式如下:
<div class="wrap">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
</div>
.wrap {
display: grid;
grid-template-columns: 200px auto 200px;
width: 100%;
.left {
height: 300px;
background-color: aqua;
}
.right {
height: 300px;
background-color: bisque;
}
.center {
height: 300px;
background-color: blueviolet;
}
}
部分答案整理自网络资源