flex是一种功能非常丰富的布局模式,是为了弥补已有的布局手段的短板。作为一种功能丰富的布局模式,它一口气解决以下全部问题:
- 如何支持横向布局和纵向布局
- 百分比模式的动态宽度和动态高度如何实现
- 子元素的排列方向和动态间距如何实现
- 子元素是否自动换行
下面我们来逐个实现上面的所有场景。
基础用法
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
.container {
height: 100px;
width: 300px;
background-color: DodgerBlue;
display: flex;
}
.item {
background-color: #f1f1f1;
width: 40px;
height: 40px;
margin: 4px;
}
上面这张图平淡无奇,看起来没有什么厉害的。
如何支持横向布局和纵向布局
flex容器默认是横向布局,即:flex-direction: row
。如果想要使用纵向布局的话,在容器上加上这样一个flex-direction: column
即可。
.container {
...
display: flex;
flex-direction: column;
}
下面的示例默认还会使用横向布局。
百分比模式的动态宽度和动态高度如何实现
使用flex: 1
来实现弹性宽度。
<div class="container">
<div class="item"></div>
<div class="item big-item"></div>
<div class="item"></div>
</div>
.container {
height: 100px;
width: 300px;
background-color: DodgerBlue;
display: flex;
}
.item {
background-color: #f1f1f1;
width: 40px;
height: 40px;
margin: 4px;
}
.big-item{
flex: 1;
}
对多个子组件同时设置flex
,则他们的宽度(或高度)会等比例分配。
<div class="container">
<div class="item"></div>
<div class="item" style="flex:2"></div>
<div class="item" style="flex:1"></div>
</div>
效果如图:
下面的两个主题是主方向和辅助方向,这两个词是我自己造的,也不知道官方的说法是啥。如果flex容器是横向布局的话(flex-direction=row),那么justify-content就是横向排列的方式,比如从头部、从尾部、居中、等分等,而align-items就是纵向怎么放置,比如居中、靠上、靠下、填充全部等。
主方向的元素排列
通过在父组件上使用justify-content
属性来控制元素在主方向上的排列方式。
justify-content 值 | 效果 |
---|---|
justify-content: center | 水平居中 |
justify-content: flex-start | 向开始方向布局(可以简单理解为靠左) |
justify-content: flex-end | 向结束方向布局(可以简单理解为靠右) |
justify-content: space-around | 左右均保持相等的距离 |
justify-content: space-between | 两边的元素靠边,然后元素左右均保持相等的距离 |
先说为什么叫flex-start
和flex-end
,而不直接叫flex-left
和flex-right
,我的理解是,因为它可以设置改变元素的物理顺序,比如:设置父组件为flex-direction: row-reverse
或flex-direction: column-reverse
,则会让元素逆序渲染。另外,还可以给子组件设置order: 2
这样的方式,来改变每个组件的呈现顺序。
然后再看看space-around
和space-between
的区别。上图为space-around
,下图为space-between
。
辅助方向的元素排列
通过在父元素上使用align-items
属性,来控制子元素在辅助方向上的元素排列。
align-items 值 | 效果 |
---|---|
align-items: center | 垂直方向水平居中 |
align-items: flex-start | 垂直方向向开始方向布局(可以简单理解为靠上) |
align-items: flex-end | 垂直方向向结束方向布局(可以简单理解为靠下) |
align-items: stretch | 垂直方向填充全部高度(不能设置height属性) |
子元素是否自动换行
通过设置父元素的flex-wrap
属性,可以设置当子元素过多时是否自动换行。
flex-wrap: wrap
自动换行flex-wrap: nowrap
不自动换行