# Flex 布局
Table of Contents
Flex 布局,即为弹性布局。
Flex 容器
要使用 Flex 布局,首先需要定义一个父容器 container。
display: flex
<div class="container"> <div>flex item</div> <div>flex item</div></div>.container { display: flex;}Flex 容器属性
- flex-direction: row^ | row-reverse | column | column-reverse;- flex-wrap: nowrap^ | wrap | wrap-reverse;- flex-flow: <flex-direction> || <flex-wrap>; (^: row nowrap)- justify-content: flex-start^ | flex-end | center | space-between | space-around | space-evenly;- align-items: stretch^ | flex-start | flex-end | center | baseline;- align-content: stretch^ | flex-start | flex-end | center | space-between | space-around;备注: ^: default(默认值)
flex-direction
该属性定义了 flex 项在容器朝哪个方向上堆叠。主要是水平方向或垂直方向上。
flex-direction: row
flex-direction: row-reverse
flex-direction: column
flex-direction: column-reverse
flex-wrap
该属性定义了 flex 项在容器上是否换行。
flex-wrap: nowrap (默认)
flex-wrap: wrap
flex-flow
该属性是flex-direction和flex-items的简写。
flex-flow: column wrap (即 flex-direction: column; flex-wrap: wrap)
justify-content
该属性定义了 flex 项在容器水平方向上的对齐方式。
justify-content: flex-start (默认)
justify-content: flex-end
justify-content: center
justify-content: space-between
justify-content: space-around
justify-content: space-evenly
align-items
该属性定义了 flex 项在容器垂直方向上的对齐方式。
align-items: stretch (默认)
align-items: flex-start
align-items: flex-end
align-items: center
align-items: baseline
align-content
该属性定义了 flex 项在容器上多行的垂直方向对齐方向, 要求flex-wrap: wrap属性。
align-content: center (需配合 flex-wrap: wrap)
align-content: flex-start
align-content: flex-end
align-content: space-between
align-content: space-around
PS: 该属性在 flex 项只有一行没有效果。
Flex 项
Flex 容器下的直接子元素就是 flex 项。
Flex 项属性
- order: <integer>; (^: 0)- flex-grow: <number>; (^: 0)- flex-shrink: <number>; (^: 1)- flex-basis: <length> | auto^;- flex: none | [ <flex-grow> <flex-shrink>? || <flex-basis> ]; (^: 0 1 auto)- align-self: auto^ | flex-start | flex-end | center | baseline | stretch;order
该属性指定了 flex 项的排列顺序,必须是整数。值越小排名越靠前,默认都为 0。
order: 3 1 2
DOM 顺序为 1、2、3
flex-grow
该属性指定了 flex 项相对于其他的 flex 项的增长量,按比例划分,负数无效。默认值为 0,表示该元素不索取父元素的剩余空间。
flex-grow: 1 / 2 / 1 (剩余空间按比例分配)
flex-shrink
该属性指定了 flex 项相对于其他的 flex 项的收缩量,按比例划分,负数无效。
flex-shrink: 3 / 1 / 1 (空间不足时按比例收缩)
flex-basis
该属性指定了 flex 项的初始长度。例如 20%, 4rem, 250px…
flex-basis: 20% / 40% / auto
flex
该属性是flex-grow, flex-shrink和flex-basis等属性的缩写。
flex: 1 (即 1 1 0%)
align-self
该属性定义了 flex 项在容器内的垂直方向的对齐方向,该属性会覆盖容器的align-items属性设置的对齐方式。
容器的 align-items 为 flex-start,中间项 align-self 为 center
Flex 相关问题
flex 项中 flex 的值
flex 是 flex-grow, flex-shrink 和 flex-basis 的简写
flex 可以设置 flex: auto(1 1 auto) 和 flex: none(0 0 auto) 两个快捷值之外,还可以设置以下方式:
- flex 取值非负整数,则 flex-grow 取该值,flex-shrink 取值为 1,flex-basis 取值 0%。
- flex 取值为长度或者百分比,则 flex-basis 取该值,flex-grow 取值为 1,flex-shrink 取值为 1。
- flex 取值为两个非负整数,则分别 flex-grow 和 flex-shrink 的值,flex-basis 取值 0%。
- flex 取值为非负数字和一个长度或者百分比,则分别视为 flex-grow 和 flex-basis 的值,flex-shrink 取值 1。
由上面规律可得知,有非负整数先赋值给 flex-grow,长度/百分比赋值给 flex-basis,三项的默认值为:flex: 1 1 0%;