图文分析 flex 布局

240 阅读2分钟

基本概念

  • Flex是Flexible Box的缩写,意为”弹性布局”,用来为盒状模型提供最大的灵活性
  • 器默认存在两根轴:水平的主轴(main axis)和垂直的交叉轴(cross axis)
  • 基本语法
    display:flex;

image.png

flex 容器属性 (主)

  1. flex-direction
  2. flex-wrap
  3. flex-flow
  4. justify-content
  5. align-items
  6. align-content
flex-directions

决定主轴的方向,子盒子在容器的排列方向

flex-direction: row | row-reverse | column | column-reverse
  • row:默认值,主轴为水平方向,起点在左边(从左往右排列)

1652510448(1).jpg

  • column:主轴为垂直方向,起点在上边(从上往下排列)

1652510595(1).jpg

  • row-reverse:主轴为水平方向,起点在右边(从右往左排列)

image.png

  • column-reverse:主轴为垂直方向,起点在下面(从下往上排列)

image.png

flex-wrap

flex-wrap 决定在一条轴上面排不下时是否换行,如何换行

    flex-wrap: nowrap | wrap | wrap-reverse 
  • nowrap: 默认值,默认不换行,在一条轴上面排不下时不换行会导致容器内盒子的宽度失效
    • 下图每个设置宽度设置为 100px,没有换行导致宽度失效,此时子盒子宽度根据容器宽度平均分配

image.png

  • wrap:换行,第一行在上方

image.png

  • wrap-reverse:换行,第一行在下方

image.png

flex-flow
  • flex-direction 和 flex-wrap 组合(简写)
    flex-flow:column wrap;
    // 第一个值 flex-direction 属性,第二个值 flex-wrap 属性

image.png

justify-content
  • 决定在主轴上面的对齐方式(排列方式)
    justify-content: flex-start | flex-end | center | space-between | space-around
  • flex-start:默认值,主轴上面左对齐

image.png

  • flex-end:主轴上右对齐

image.png

  • center:主轴上居中

image.png

  • space-between:俩端对齐,盒子之间间隔相等

image.png

  • space-around:盒子之间间隔相等,相邻的盒子之间的间隔与是容器的俩倍

image.png

image.png

aling-items
  • 决定在副轴(交叉轴)上排列方式
    aling-items:flex-start | flex-end | center | baseline | strech
  • flex-start:默认值,副轴上起点对齐(上对齐)

image.png

  • flex-end:副轴上终点对齐(下对齐)

image.png

  • center:副轴上居中对齐

image.png

  • baseline:一项目中的文字果没有文字则在底部对齐 image.png

image.png

  • stretch:如果容器内盒子没有设置高度或设为 auto,子盒子会占满容器高度

image.png

align-content
  • 定义多跟轴线的对齐方式,如果只有一个根轴线则不生效(需使用 flex-flow 设置主轴和换行方式,个人理解)
  • 只针对 flex-flow:row wrap 添加图文
    flex-flow:row wrap | row wrap-reverse | column-wrap | column wrap-reverse
    align-content: flex-start | flex-end | center | space-between | space-around | stretch
  • flex-start
    • row wrap

      image.png

    • row wrap-reverse

      image.png

    • column warp image.png

    • column wrap-reverse

      image.png

  • flex-end
    • row wrap

      image.png

    • row wrap-reverse

      image.png

    • column wrap

      image.png

    • column wrap-reverse

      image.png

  • center
    • row wrap

      image.png

    • row wrap-reverse

      image.png

    • column wrap

      image.png

    • column wrap-reverse

      image.png

  • space-between
    • row wrap

      image.png

    • row wrap-reverse

      image.png

    • column wrap

      image.png

    • column wrap-reverse

      image.png

  • space-around
    • row wrap

      image.png

    • row wrap-reverse

      image.png

    • column wrap

      image.png

    • column wrap-reverse

      image.png

  • stretch
    • 子盒子没有设置高度时,flex-direction:row | row-reverse 时,会填充高度 image.png