秦小

CSSMM4E 笔记 - 3.17 - 使用Flexbox的现代Web布局

Flexbox简介

  • Flex 容器 - 通常为div
    display: [--webkit--]flex
    自动添加前缀Autoprefixer: https://github.com/postcss/autoprefixer
    “Can I use” 列出了实时更新的浏览器支持的CSS特性: http://caniuse.com/#info_about
    Flex容器 不是block-level元素.
  • Flex 子项(Flex items) - flex 容器的所有 直接 子元素
    Flex 子项 margins 不塌陷(don’t collapse)

Flex容器的属性

display: flex; - 成为容器

让元素成为Flex容器

flex-flow - 排列方式

Flex子项的排列方式(行列,起始端,是否断行/列)

1
2
3
4
.flex-container {
flex-flow: { row | row-reverse | column | column-reverse } { wrap | nowrap | wrap-reverse };
flex-flow: row wrap;` = `flex-direction: row; flex-wrap: wrap;
}

  • row - Default, side by side
  • row-reverse - side by side but reverse
  • column - top to bottom
  • column - reversely top to bottom
  • nowrap - Default, keep all items in the single row or column
  • wrap - let items that don’t fit inside the container’s width drop down to new (or over to a new column).
  • wrap-reverse - like wrap, and reverse

justify-content - 子项在行中的对齐方式

只当子项都设置了宽度并且子项的总宽度小于容器时才起作用.

  • flex-start - 左对齐; if row-reverse 右对齐?
  • flex-end - 右对齐, if row-reverse 左对齐.
  • center - 居中对齐
  • space-between - 两端对齐, 将空白平均填充在items两两之间(between)
  • space-around - 类似space-between, 同时在所有items两端增加空白

Markdown

align-items - 不同高度子项的垂直对齐方式

  • flex-start - top
  • flex-end - bottom
  • center - center
  • baseline - basline of the first element within the flex
  • stretch - Default stretch to the same height

Markdown

align-content - 断行(wrap)时怎样排列子项

满足两个条件时起作用: 1. flex 容器必须为 wrap 2. flex 容器高度大于行高和

  • flex-start - align top for rows 以行为单位
  • flex-end - align bottom for rows
  • center - center for rows
  • space-between - 纵向两端对齐, 将空白平均填充到row两两之间
  • space-around - 同上, 但同时在top, bottom增加空白.
  • `stretch`` - stretch items in same row to same height

Flex子项的属性

order - 对items排序

order 的默认值应该在 -1 and 1 之间

align-self - 覆盖容器的 align-items

flex 关键属性

flex: flex-grow flex-shrink flex-basis;
默认值: flex: 0 1 auto

使用 flex: number 时, flex-basis被设置为0%; 此时flex item宽度完全由flex-grow决定

flexbox 的解救: http://philipwalton.github.io/solved-by-flexbox/
w3 - flexbox: https://drafts.csswg.org/css-flexbox/

  • flex-grow - number indicates the relative width of that flex item
  • flex-shrink - number 当所有items总的width > cantainer的width时, 控制item能多少量的压缩
  • flex-basis - sets a base width for a flex item (100px, 5em, or 50%)

flex-grow 像一个膨胀的力, flex-shrink像一个摩擦力, flex-basis是一个基础的状态

浏览器怎样计算flex item的宽度

1
2
3
4
/* When the container width is larger than total width of items,
the __flex-shrink__ has no effect */
let delta = cantainer_width / item_count;
item_width_n = item__flex-basis__n + (delta * item__flex-grow__n)

再看flex-shrink

这个值只是设置nowrap时才重要; 定义当items总宽度>container宽度时怎样压缩items.

Wrapping Flex Items