介绍:

长久以来,CSS 布局中唯一可靠且跨浏览器兼容的创建工具只有 floatspositioning。这两个工具大部分情况下都很好使,但是在某些方面它们具有一定的局限性,让人难以完成任务。
Flex容器给出了更好的解决方法,内容上分为容器和项目,布局上分为一个主轴和一个交叉轴。

container样式:

display: flex 或 display: inline-flex,表明使用flex布局。

  1. .container{
  2. display: flex;
  3. }

flex与inline-flex的区别和block与inline-block的区别类似:占据一整行还是一行可以由多个。

流动方向(flex-direction)

  1. flex-direction:row 从左往右横向排列(默认)
  2. flex-direction:row-reverse 从左往右横向排列
  3. flex-direction:column 从上到下排列;
  4. flex-direction:column-reverse 从下到上排列
  5. 缩写:flex-flow: direction wrap

    换行(flex-nowrap)

  6. flex-wrap:nowrap 不换行,默认,具有弹性

  7. flex-wrap:wrap 换行
  8. flex-wrap:wrap-reverse 从下往上换行

    主轴对齐方式(justify-content)

  9. justify-content:flex-start 左对齐

  10. justify-content:flex-end 右对齐
  11. justify-content:center 居中对齐
  12. justify-content:space-between 左右靠边,中间间隙相同
  13. justify-content:space-around 左右间隙相等
  14. justify-content:space-evenly 所有间隙相等(包括最左和最右)

reverse后开头结尾方向也会对调

次轴对齐方式(align-items)

  1. align-items:flex-start 上对齐
  2. align-items:flex-end 下对齐
  3. align-items:center 中间对齐
  4. align-items:streth 拉长,等高(默认)
  5. align-items:baseline 基线对齐

    多行内容及周围空间分配(align-content)

  6. align-content:flex-start 从上到下

  7. align-content:flex-end 从下到上
  8. align-content:center 居中
  9. align-content:stretch 拉伸以充满容器
  10. align-content:space-between 上下靠边,其他间隙相同
  11. align-content:space-around 两边间距相等

item样式:

排序(order)

默认为0, 从大到小排列,可以为负数

空间分配

  1. flex-grow:number 平均分空间,按比例分配每个item空间
  2. flex-shrink:number 在像素不够时,先把哪个变窄,可写0,防止变窄
  3. 缩写flex:grow shrink width

    定制 align-items(item-self)

    属性值跟align-itenms相同,作用于单个元素