Flex
布局又成为弹性盒子布局。
它有两条轴:主轴 main axis
和交叉轴 cross axis
。
一般情况下,主轴指的是水平方向的轴线,交叉轴指的是垂直方向的轴线(会受到 flex-direction
的影响)。
它的属性分为两类:
- 容器属性。
- 项目属性。
12-1.容器属性
该系列属性设置在容器上。
12-1-1.flex-direction
flex-direction
设置主轴方向。
其可选值有以下:
row
默认值row-reverse
column
column-reverse
12-1-2.flex-wrap
flex-wrap
设置是否换行。
其可选值有以下:
nowrap
默认值wrap
wrap-reverse
12-1-3.flex-flow
flex-flow
是 flex-direction
和 flex-wrap
的简写属性。
其用法:
flex-flow: row-reverse wrap;
12-1-4.justify-content
justify-content
设置主轴方向的排列方式。
其可选值有以下:
center
flex-start
默认值flex-end
space-between
space-around
space-evenly
12-1-5.align-items
align-items
设置交叉轴方向的元素排列方式。
其可选值有以下:
center
flex-start
flex-end
12-1-6.align-content
align-content
设置交叉轴方向的轴线排列方式。
其可选值有以下:
stretch
默认值center
flex-start
flex-end
space-between
space-around
space-evenly
The align-content property modifies the behavior of the flex-wrap property. It is similar to align-items, but instead of aligning flex items, it aligns flex lines
TIP
当容器有固定高度,且触发了 flex-wrap
时,元素交叉轴方向的占用空间会被拉伸。
平时开发注意不到上述影响,是因为通常不会给外层容器设置固定高度。
12-2.项目属性
该系列属性用来设置项目。
12-2-1.order
order
设置项目的排列顺序 数值越小,排列越靠前,默认为 0
。
order: 1;
12-2-2.flex-basis
flex-basis
设置在分配多余空间之前,项目占据的主轴空间。浏览器会根据这个属性来计算主轴是否有多余空间。
它的默认值为 auto
,即项目的本来大小。
12-2-3.flex-grow
flex-grow
设置项目的放大比例,默认为 0
,即如果存在剩余空间时也不放大。
12-2-4.flex-shrink
flex-shrink
设置项目的缩小比例,默认为 1
,即如果空间不足,该项目将缩小。不能设置负值。
12-2-5.flex
flex
是 flex-grow
, flex-shrink
和 flex-basis
的简写,后两个属性可选。
默认值为:flex:0 1 auto;
如果设置为 flex: 1
; 则等于 flex-grow: 1; flex-shrink: 1; flex-basis: 0%;
。
12-2-6.align-self
align-self
用来设置某个项目的排列方式。
align-self: auto | flex-start | flex-end | center | baseline | stretch;
align-items
针对的是所有项目,而 align-self
则是针对某个项目,二者表现形式一致。
唯一区别就是 align-self
多了个 auto
(默认值),表示继承自 flex
容器的 align-items
属性值。其他属性值含义一模一样。