An Interactive Guide to Flexbox
这篇文章较为深入地解释了 Flexbox 的工作模式和使用方法,文章提到了几个我不太熟悉的知识点:
gap:每个 item 之间的间距,我之前一直用 margin,但一旦 wrap,每一行的第一个或最后一个 item 会出现多余的间距,gap 可避免这个问题;align-self:align-items 用在 Flexbox 的 container 中,而 align-self 用在每一个 item 中,事实上我们可以把 align-items 看成是 align-self 的 shorthand,在 container 中使用了 align-items,然后在某个 item 中使用 align-self,可对这个 item 单独设置不同于其他 item 的对齐方式,要注意的是 justify-self 在 Flexbox 中无效;width 属性可能不会被严格执行,因为这时候的宽度是 hypothetical(假设)宽度,height 也是,设置 flex-wrap: wrap 可暂时避免尺寸被压缩到低于假设值;flex-basis:类似 width 或 height,但如果同时设置了 width 或 height,flex-basis 优先,flex-basis 的意思是在 flex-shrink 或 flex-grow 时,是在 flex-basis 设置的值开始压缩或伸展的,只作用于 primary axis 这个方向;In a Flex row,
flex-basisdoes the same thing as width. In a Flex column,flex-basisdoes the same thing asheight. It's likewidthorheight, but pegged to the primary axis, like everything else. It allows us to set the hypothetical size of an element in the primary-axis direction, regardless of whether that's horizontal or vertical.
align-items 和 justify-content 的值才不完全相同,也正因为这个原因 justify-self、justify-items 在 Flexbox 中无效;
margin: auto:可在某个 item 中使用 margin: auto、margin: auto 0、margin: 0 auto 使该 item 上下左右居中显示;
align-content:主要用在 flex-wrap: wrap 的情况下,align-items 是对同一行中的 item 进行设置,而 align-content 其实是把每一行分别看作一个整体 item(这个整体 item 包括了多个 item,所以也叫 content)再 align-items,所以 align-content 可能的值和 align-items 是一样的;
min-width:一些 html 元素有浏览器赋予的默认最小尺寸,比如 text input 默认的最小宽度是 170px ~ 200px(不同浏览器之间不同),flex-shrink 不会无限压缩这些元素的尺寸,于是可能出现 overflow,对于这些元素,设置 min-width: 0 即可避免 overflow;
总结以下几个容易混淆的属性:
align-items:作用于每一个 item,在垂直于 primary axis 的方向上布局,可看作是 align-self 的 shorthand;align-content:主要搭配 flex-wrap: wrap 使用,把每一行当作一个 item 进行布局;align-self:类似 align-items,但用在某个 item;justify-content:在 primary axis 方向上布局;justify-items:在 Flexbox 中无效;justify-self:在 Flexbox 中无效;place-items:justify-items 和 align-items 的 shorthand;place-content:justify-content 和 align-content 的 shorthand;相关笔记:
margin:auto 居中元素还有一个额外好处,可避免被居中的元素显示不完整;place-items、place-content 居中元素;