在使用flex是一个流式伸缩布局方式,比如正常下弹性盒子flex实现三栏布局,但有时我们想实现多行或指定一行多少个。也是有方法可以实现的。
先看一个flex实现三栏布局,用一个容器container包裹三栏,设置comtainer容器的display属性为flex,左右栏设置宽度为300px,中间栏设置flex:1,这里的1表示宽度比例,具体数值取决于其它盒子的flex值,由于这里其它盒子宽度固定,所以中间栏会自动填充:
html>
三栏布局html*{
margin: 0;
padding: 0;
}
.container{
display: flex;
}
.left{
background-color: #00FFFF;
width: 300px;
height: 100px;
}
.center{
height: 100px;
flex: 1;
background: #f296ff;
}
.right{
height: 100px;
background-color: #6ee28d;
width: 300px;
}
效果如图:
flex实现多行多列的多种方式
先看一下效果:
灵活变通:通过百分比和折行来实现,是n列就把百分比变为100/n(%),如果是3列,那么可以把50%改成33.333%,如果是4列,那么改成25%,依次类推,
下面是2行2列的多种写法实现
1.父容器设置为flex布局,并允许折行
.flex-outer {
display: flex;
flex-wrap: wrap;
}
2.子容器设置样式
.flex-outer article {
background: limegreen;
border: 1px solid #eee;
box-sizing: border-box;
color: #fff;
padding: 15px;
}
3.多种方法给每个子容器设置50%的宽度,实现2行2列
方法(1) :flex合并属性 flex: 1 0 50%;
/* flex合并属性 */
.flex-outer.flex-attr article {
flex: 1 0 50%;
}
1.flex合并属性 flex: 1 0 50%;
1
2
3
4
方法(2) : 基准属性 flex-basis: 50%;
/* flex-basis */
.flex-outer.flex-basis article {
flex-basis: 50%;
}
2.基准属性flex-basis: 50%;
1
2
3
4
方法(3): 设置宽度 width: 50%;
/* 设置width */
.flex-outer.width-attr article {
width: 50%;
}
3.设置widthwidth: 50%;
1
2
3
4
完整实例代码:
html>
flex实现两行两列.flex-outer {
display: flex;
flex-wrap: wrap;
}
.flex-outer article {
background: limegreen;
border: 1px solid #eee;
box-sizing: border-box;
color: #fff;
padding: 15px;
}
/* flex合并属性 */
.flex-outer.flex-attr article {
flex: 1 0 50%;
}
/* flex-basis */
.flex-outer.flex-basis article {
flex-basis: 50%;
}
/* 设置width */
.flex-outer.width-attr article {
width: 50%;
}
pre {
display: flex;
justify-content: space-between;
}
1.flex合并属性 flex: 1 0 50%;
1
2
3
4
2.基准属性flex-basis: 50%;
1
2
3
4
3.设置widthwidth: 50%;
1
2
3
4