Flexbox

⏱2020-03-02 🔖

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-betweenspace-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-directionflex-wrap,还设置单个 item 的 order 属性。

flex-wrap

可以和 align-content 属性一起使用。

flex,弹性效果

1
2
3
4
5
6
注意:
flex: 0; -> flex-basis: 0;
flex: 1; -> flex-grow: 1;

flex 属性就是用于计算每个 item 应该被弹性分配多少 width/height 的属性。
reference: https://juejin.im/post/5dedb28ef265da33b12e98cd

flex-grow

  1. 实现 grow 弹性效果的基础是 container 有额外的空间可以分配给 item。
  2. 如果 items 的总长度小于 flex container 的长度,那么剩余的长度通过 flex-grow 的比例来分配。
  3. 计算 grow 之后的长度不能超过 max-width/height

计算方法,先计算出 container 的剩余空间,再按照 grow 的比例分发剩余空间。

flex-shrink

  1. 实现 shrink 弹性效果的基础是每个 item 内部有额外空间可以收缩。
  2. 如果 items 在 main axis 上的长度没有超过 flex container 的大小,flex-shrink 不会生效。
  3. 计算 shrink 之后的长度不能低于 min-width/height

计算方式:

1
2
3
4
5
overflow = container.length - total_length
total_basis = (item1.length * item1.unit) + (item2.length * item2.unit)

item1.shrink_rate = (item1.lenght * item1.unit) / total_basis
item1.length = item1.length - (overflow * item.shrink_rate)

Shrink 的极限:如果 item shrink 小于 min-width/height,则不会再 shrink。剩余的元素通过以上规则重新 shrink。

1
2
3
4
5
6
# 案例:https://www.w3schools.com/code/tryit.asp?filename=GCFOVKJ7NOEM
overflow = 800 - 250
total_basis = 2000
item1.shrink_rate = 0.4
item1.length = 400 - overflow * 0.4
# item1.length -> 180

如何计算剩余/溢出长度
通过 items 的长度来计算 grow/shrink 时,item 的长度通过以下优先度获取:

  1. flex-basis
  2. width/height
  3. box model 的自动分配长度,即被子元素撑起来的长度

另外,一下这种做法相当于为 section 隐式设置了 min-width: 100px

1
2
3
<section>
<div style="width: 100px"></div>
</section>