CSS:flex布局

1,424 阅读1分钟

css的flex主要由以下两个标签组成:

  1. container(容器)
  2. items(项目)

container样式

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

.container{
  display: flex;
}

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

  • 流动方向(flex-direction)

流动方向表明item的布局

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

  1. flex-wrap:nowrap 不换行,默认,具有弹性
  2. flex-wrap:wrap 换行
  3. flex-wrap:wrap-reverse 从下往上换行
  • 主轴对称方式(justify-content)

  1. justify-content:flex-start 左对齐
  2. justify-content:flex-end 右对齐
  3. justify-content:center 居中对齐
  4. justify-content:space-between 左右靠边,中间间隙一样
  5. justify-content:space-around 左右间隙相等
  6. justify-content:space-evenly 所有间隙相等(包括最左和最右)
  • 次轴对称方式(align-items)

  1. align-items:flex-start 上对齐
  2. align-items:flex-end 下对齐
  3. align-items:center 中间对齐
  4. align-items:streth 拉长,等高(默认)
  • 多行分布(align-content)

  1. align-content:flex-start 从上到下
  2. align-content:flex-end 从下到上
  3. align-content:center 居中
  4. align-content:stretch 填满高度
  5. align-content:space-between 上下靠边居中
  6. align-content:space-around 两边间距相等对齐

item样式

  • 排序(order)

默认为0,从小到大排列

  • 空间分配

  1. flex-grow:1; 平均分空间,按比例分配每个item空间
  2. flex-shrink:1; 在像素不够时,先把哪个变窄,可写0,防止变窄
  • 上下对齐

  1. align-self:flex-end; 靠下
  2. align-self:flex-end; 靠上