flex 弹性盒布局模型

1. 什么是 flex

Flexible Box 简称 flex,意为"弹性布局",可以简便、完整、响应式地实现各种页面布局。

  • 采用 Flex 布局的元素,称为 flex 容器(container)。
  • 它的所有子元素自动成为容器成员,称为 flex 项目(item)。
  • 容器中默认存在两条轴——主轴和交叉轴,呈 90 度关系。项目默认沿主轴排列,通过 flex-direction 决定主轴方向。
  • 每根轴都有起点和终点,这对元素的对齐非常重要。

2. 容器属性

  • display: flex:定义 flex 容器。
  • justify-content: flex-start | flex-end | center | space-around | space-between | space-evenly:主轴对齐。
  • flex-wrap: wrap | nowrap | wrap-reverse:是否换行。
  • flex-flow: <flex-direction> <flex-wrap>:上面两个属性的简写。
  • flex-direction: row | row-reverse | column | column-reverse:主轴方向。
  • align-items: flex-start | flex-end | center | stretch | baseline:交叉轴单行对齐。
  • align-content: flex-start | flex-end | center | space-around | space-between | stretch:交叉轴多行对齐。

3. 项目属性

  • order: <number>:定义项目排列顺序,默认 0,越小越靠前。
  • flex-grow: <number>:定义项目的放大比例,默认 0。
  • flex-shrink: <number>:定义项目的缩小比例,默认 1。
  • flex-basis: <length> | auto:定义在分配多余空间之前项目占据的主轴空间。
  • flex: <flex-grow> <flex-shrink> <flex-basis>:上面三个属性的简写。常用 flex: 1 表示占满剩余空间。
  • align-self: auto | flex-start | flex-end | center | baseline | stretch:覆盖 align-items。

补充:

  • flex: 1 是最常用的简写,等价于 flex: 1 1 0%,意为"占满剩余空间"。
  • flex 布局的浏览器兼容性已经非常好(IE10+ 需加 -ms- 前缀),现代项目可放心使用。
  • 与 grid 二维布局相比,flex 是一维布局,适合行/列方向上的对齐;复杂的二维网格优先选择 grid。