Flexbox
Why flexbox
Before the Flexbox Layout module, there were four layout modes:
- Block, for sections in a webpage
- Inline, for text
- Table, for two-dimensional table data
- Positioned, for explicit position of an element
The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.
Flexbox 各种常用属性
justify-content
Aligns flex items along the main axis.
flex-start: Items align to the left side of the container.flex-end: Items align to the right side of the container.center: Items align at the center of the container.space-between: Items display with equal spacing between them.space-around: Items display with equal spacing around them.
space-between 和 space-around 的区别:between 会让 flex items 接触边缘,而 around 会保留等宽的周边空间,不会接触边缘。
align-items
Aligns flex items along the cross axis.
flex-start: Items align to the top of the container.flex-end: Items align to the bottom of the container.center: Items align at the vertical center of the container.baseline: Items display at the baseline of the container.stretch: Items are stretched to fit the container.
使用 align-self 属性可以单独设置单个 item 相对 cross axis 的位置。
flex-flow
分为 flex-direction 和 flex-wrap,还设置单个 item 的 order 属性。
flex-wrap
可以和 align-content 属性一起使用。
flex,弹性效果
1 | 注意: |
flex-grow
- 实现 grow 弹性效果的基础是 container 有额外的空间可以分配给 item。
- 如果 items 的总长度小于 flex container 的长度,那么剩余的长度通过
flex-grow的比例来分配。 - 计算 grow 之后的长度不能超过
max-width/height。
计算方法,先计算出 container 的剩余空间,再按照 grow 的比例分发剩余空间。
flex-shrink
- 实现 shrink 弹性效果的基础是每个 item 内部有额外空间可以收缩。
- 如果 items 在 main axis 上的长度没有超过 flex container 的大小,
flex-shrink不会生效。 - 计算 shrink 之后的长度不能低于
min-width/height。
计算方式:
1 | overflow = container.length - total_length |
Shrink 的极限:如果 item shrink 小于 min-width/height,则不会再 shrink。剩余的元素通过以上规则重新 shrink。
1 | # 案例:https://www.w3schools.com/code/tryit.asp?filename=GCFOVKJ7NOEM |
如何计算剩余/溢出长度
通过 items 的长度来计算 grow/shrink 时,item 的长度通过以下优先度获取:
flex-basiswidth/height- box model 的自动分配长度,即被子元素撑起来的长度
另外,一下这种做法相当于为 section 隐式设置了 min-width: 100px
1 | <section> |