By Ali Tao, F(X) Team – Desert

Flexbox layout is one of the most popular Web layout methods, which brings great flexibility and convenience to Web developers in completing the UI layout of pages or components. But also because of its great flexibility, there are some hidden details, many of which would be missed if you were not very familiar with Flexbox or its specifications, and these details can be confusing or even cause trouble.

This time, while optimizing ImgCook’s Flexbox layout, I reread Flexbox specs and realized that I had left out some important information. For this reason, in this article, Flexbox layout, CSS writing mode, logical properties, and alignment are combined together to organize a note, hoping to help students who want to understand or use Flexbox to encounter pain.

Some terms and concepts

Flexbox term

The unification of terminology helps us to better discuss and solve problems later. Use the following figure to describe the terms in Flexbox:


The concept of the Main Axis and the side Axis is only found in the Flexbox layout. The horizontal direction is not always the Main Axis and the vertical direction is always the Cross Axis. Axes and side axes are affected not only by flex-direction values in Flexbox, but also by the writing mode and direction of CSS and the DIR attribute of HTML.

Block axis and inline axis

CSS Box Alignment Module Level 3 introduces two new concepts, namely Block Axis and Inline Axis:

  • A block axis is an axis that extends vertically across the inline axis along the layout direction of a block (such as a paragraph element)
  • An inline axis is the axis along which the words of a sentence flow in a particular writing pattern. For example, in English or Chinese, the inline axis is horizontal


A Block Axis is also called a Column and an Inline Axis is also called a Row:


Although the Flexbox specification and Grid specification have their own descriptions of Alignment so far, CSS provides box-alignment modules for Alignment. Since then, the terms “block axis” and “inline axis” are more commonly used. Combined with the Flexbox layout, the axis corresponds to:

  • The Inline Axis is also referenced to the Main Axis in Flexbox
  • The Block Axis is also referenced to the Cross Axis in Flexbox

The block axis and inline axis are also affected by the WRITING mode and direction of the CSS and the DIR attribute of the HTML. However, in the Flexbox layout, it is also affected by the Flex-direction property.

Writing mode

The writing-mode and direction properties in the CSS Writing Modes Level 3 specification, as well as the DIR property in HTML, affect the spindle and side axes in Flexbox, changing the orientation of the spindle and side axes.



Logical properties

With the advent of Block axis, Inline axis, and write mode, we have Block Start, Block End, Inline Start, and Inline End:


If placed in Flexbox layout:

  • Inline Start is the same as Main Start in Flexbox layout
  • Inline End is equivalent to Main End in Flexbox layout
  • Block Start is equivalent to Cross Start in Flexbox layout
  • Block ends are equivalent to Cross ends in Flexbox layouts.

Block-start, block-end, inline-start, and Inline-end are introduced in the CSS Logical Properties and Values Level 1 specification, but they are similar to Flexbox, Flex -start, start, flex-end, and end in Box Alignment in Grid are not identical and are not concepts in the same domain. These attributes correspond to the physical attributes of top, right, bottom, and left:


That is, after the introduction of CSS logical properties, the CSS box model will be divided into physical box model and logical box model:


CSS properties have since been divided into logical and physical properties:


Note that CSS logic attributes are also affected by the CSS writing-mode, directioin attribute, and HTML dir attribute, and vary in different combinations:


Surplus space (available space) and insufficient space

In the Flexbox layout module, the Flex container may contain one or more Flex projects. The Flex container and Flex project have their own size, so there are situations where the sum of the Flex project size is greater or smaller than the Flex container:

  • When the sum of all Flex project sizes is less than the Flex container, the Flex container has extra Space that has not been filled. This Space is called the Flex container’s Free Space.
  • When the sum of all Flex project sizes is greater than the Flex container, the Flex container does not have enough Space for all Flex projects (Flex projects overflow the Flex container), and the extra Space is called Negative Free Space, also called Negative Space



Flex containers and Flex projects

Use display on an element to set the value to flex or inline-flex. The container becomes a Flex container, and its children include text nodes and pseudo-elements.


Specific scenarios for using Flex and inline-Flex:


If an element explicitly sets display to flex or inline-flex, a Flex project will size itself by its content size when it does not explicitly set sizing properties.

  • Set todisplay: flexWhen the Flex container does not explicitly set a width-related property, the width of the Flex container is the same as its parent container (equivalent towidth: 100%
  • Set todisplay: inline-flexWhen the Flex container does not explicitly set width-related properties, the width is equal to the width sum of all Flex projects


When all Flex items in the Flex container are larger than the width of the Flex container:

  • Set todisplay: flexThe Flex project overflows the Flex container
  • Set todisplay: inline-flex, the Flex project will stretch the Flex container, potentially causing the Flex container to overflow its parent (or ancestor) element


Display: inline-flex is best used in combination with min-width and min-height. Setting width and height explicitly is not recommended.

When display is set to Flex, the Flex container behaves like a block container, but it is actually a Flex container with the context format FFC (Flexbox Formatting Content), Therefore, some layout attributes used on Block Formatting Content are no longer applicable, such as:

  • CSScolumn-*Property has no effect on the Flex container
  • CSSfloat  和 clearProperties do not work on Flex projects and do not take Flex projects out of document flow
  • CSSvertical-alignProperties have no effect on Flex projects
  • CSS pseudo-elements::first-line  和 ::first-letterDoes not work on Flex containers, and Flex containers do not provide first line or initial formatting for their ancestors

Note that if the display element is inline-flex and the element explicitly sets float or position to relative, absolute, or fixed, Display evaluates to flex, so the flex container behaves the same as display: flex.

Properties applied to the Flex container


Specify spindle direction

Using flex-direction explicitly in the Flex container allows you to specify the spindle direction. If you do not explicitly set the flex-direction property, the Flex container uses its default value row.


The diagram above only shows that the reading mode is LTR(left-to-right). Without a special declaration, the following document does not list different diagrams based on the reading mode (i.e. the writing-mode of CSS, direction, and the DIR attribute of HTML).

Unless you need to explicitly change the spindle orientation, you need to explicitly set Flex-Directioin on the Flex container, such as in the following version arrangement:


_flex-direction: column _

Row-reverse, which is the opposite of the default value row, applies to layout scenarios like this:


In a Flexbox layout, flex-direction also has an effect on the order in which Flex items are arranged when specifying the flex container’s main axis (this is great if you want to do the opposite direction without changing the DOM structure). In addition to flex-direction, you can also use the order attribute explicitly in a Flex project, and you can sort it any way you want without affecting the DOM structure.

When using Flexbox layout in imgCook, Flex direction is explicitly set on the Flex container, even though the default is row. In layout algorithm optimization, you can do this by explicitly setting flex-direction on the Flex container only if it is not row:


Control whether Flex items are wrapped (Flex rows)

Use flex-wrap to control how a Flex project wraps a Flex container:


Setting flex-wrap takes effect only if the sum of all Flex project widths is greater than the Flex container spindle size.

Flex-wrap values that are not nowRap (wrap and wrap-reverse) can make a Flex project newline (column) explicit, where wrap-reverse behaves the opposite of wrap.

Combined effect Your performance
Results 1


Results 2


The effect of 3


The effect of 4


The effect of 5


Results 6


Results 7


Results 8


Flex-direction and flex-wrap can be abbreviated to **flex-flow **. Flex-flow can be used with only one explicit value, or with two explicit values:

  • flex-flowOnly one value is explicitly set, and the value and<flex-direction>And when I match,flex-wrapWill the valuesinitial
  • flex-flowOnly one value is explicitly set, and the value and<flex-wrap>And when I match,flex-directionWill the valuesinitial
  • flex-flowWhen you explicitly set two values,flex-directionflow-wrapThere is no order of points, canflex-flow: column wrapflex-flow: wrap columnequivalent

Spindle alignment

Use context-content in the Flex container to control the alignment of Flex items along the Flex container axis and to allocate the remaining space in the Flex container axis. Use context-content to allocate Flex container space, primarily by aligning the space to either side of the Flex project in a different way, controlling the spacing between Flex projects.

Illustration-content exists in two specifications:

  • CSS Flexible Box Layout Module Level 1
  • CSS Box Alignment Module Level 3

In the Flexbox layout module, justify-content can be either of the following:


Notice the difference between space-between, space-around, and space-instituted:


  • space-betweenThe beginning edge of the box of the first Flex item is aligned with the beginning of the Flex container spindle, the end edge of the box of the last Flex item is aligned with the end of the Flex container spindle, and the other adjacent Flex items are equally spaced. When there is only one Flex project in the Flex container, it behaves andflex-startequivalent
  • space-aroundThe spacing between the start edge of the box of the first Flex item and the start edge of the box of the last Flex item and the end edge of the box of the last Flex item is equal to the end edge of the Flex container spindle, and equal to half the spacing between the other two adjacent Flex items. When there is only one Flex project in the Flex container, it behaves andcenterequivalent
  • space-evenlyThe spacing between the start edge of the box of the first Flex item and the start edge of the box of the last Flex item and the end edge of the box of the last Flex item is equal to the distance between the start edge of the box of the first Flex item and the start edge of the Flex container spindle, and equal to the distance between the other two adjacent Flex items. When there is only one Flex project in the Flex container, it behaves andcenterequivalent

If the Flex container has no extra space left, or if the space left is negative, the value of justify-content looks like this:

  • flex-startCauses the Flex project to overflow at the end of the Flex container spindle
  • flex-endCauses the Flex project to overflow at the start of the Flex container spindle
  • centerCauses The Flex project to overflow at both ends of the Flex container
  • space-betweenflex-startThe same
  • space-around  和 centerThe same
  • space-evenlycenterThe same

In a Flexbox layout, you can use these properties to control the remaining space of the Flex container, such as:


Alignment of side axis

Use align-items in the Flexbox container to control the alignment of Flex items along the side axis.


The default value of align-items is stretch, but Flex items will only be stretched to fill the Flex container if the Flex project explicitly sets the height (or width) value.

If the Flex container has no free space or negative free space is:

  • flex-startCauses the Flex project to overflow at the end of the Flex container side axis
  • flex-endCauses the Flex project to overflow at the start of the Flex container’s side axis
  • centerCauses The Flex project to overflow on both sides of the Flex container side axis
  • baselineCauses the Flex project to overflow at the end of the Flex container side axis, somewhat like thisflex-start

Multi-row (column) alignment

Align-content only works when the Flex container does not have enough space (the sum of the widths of all Flex items is greater than the Flex container spindle size) and flex-wrap is explicitly set to non-wrap.


Align-content behaves a bit like context-Cotent controls the alignment of Flex items in the main axis (allocating Flex container spindle space), while align-content can be used to control multi-line states, Alignment of rows on the Flex container side axis (allocates Flex container side axis remaining space). You can think of the entire line in the align-content state as a single Flex project in the context-content state.

Align-content is also a bit different in that it has a stretch value. When the sum of the dimensions of all rows in the Flex container is greater than the size of the Flex container’s side axis (there is no available space on the Flex container side axis or the available space is negative), the values behave:

  • flex-startCauses the Flex container row to overflow at the side axis end point
  • flex-endCauses the Flex container row to overflow at the beginning of the side axis
  • centerCauses Flex container rows to overflow at both ends of the side axis
  • stretchPerformance behavior is similar toflex-start
  • space-aroundPerformance behavior is similar tocenter
  • space-betweenPerformance behavior is similar toflex-start
  • space-evenlyPerformance behavior is similar tocenter

Spacing (row to row, column to column)

Gap controls the spacing between Flex items, but ignores the spacing between Flex items and Flex container edges:


Properties applied to Flex projects

Alignment of Flex projects themselves

You can use context-content, align-content, and align-items on the Flex container to allocate space on the main and side axes of the Flex container (to control the alignment of all Flex items in the Flex container). If you need to manipulate the alignment of individual Flex items, you can use align-self:


Align-self = align = self


Align-items in the Flex container will not be overwritten when the Flex project align-self is explicitly set to auto; In addition, if you explicitly set margin to auto on a Flex project, the align-self value of the Flex project will be invalidated.


Align-self is useful in scenarios like the one above.

Flex project Sequencing

Using Flex-direction in a Flex container aligns all Flex items in a Flex container in the “LTR”, “RTL”, “TTB”, or “BTT” directions.

  • LTRflex-driection: row
  • RTLflex-direction: row-reverse
  • TTB :  flex-direction: column
  • BTT :  flex-direction: column-reverse

On Flex projects, you can also use order to specify a specific value and sort Flex projects without changing the DOM structure, where the larger the value is, the further it goes:


In addition to flex-direction, you can also set order in the Flex project:


Flex projects scale calculations

The Flex property used in a Flex project to scale itself based on the available space of the Flex container consists of three subproperties: flex-basis, Flex-shrink, and Flex-grow. Each of these attributes has an initial value:

  • flex-growThe initial value of is0
  • flex-shrinkThe initial value of is1
  • flex-basisThe initial value of isauto

That is, the three flex subproperties: flex-grow, flex-shrink, and Flex-basis. These three properties control the Flex project as follows:

  • flex-grow: Set the expansion ratio of Flex projects, so that Flex projects get the amount of Flex container Free Space (Positive Free Space), that is, Flex projects may grow
  • flex-shrink: Set the Flex project shrinkage ratio so that the Flex project minus the Negative Free Space of the Flex container, that is, the Flex project may become smaller
  • flex-basis: Size of a Flex project before it expands or contracts, which specifies the initial size of the Flex project along the main axis

The Flex property can specify 1 value (single-valued syntax), 2 values (two-valued syntax), or 3 values (three-valued syntax).

Single-valued syntax: The value must be one of the following:

  • A unitless number (<number>), such asflex: 1At this point it will be taken as<flex-grow>The value of the
  • A valid width (width) value, for exampleflex: 30vwAt this point it will be taken as<flex-basis>The value of the
  • keywordsnoneautoinitial(The initial value)

Double-valued syntax: The first value must be a unitless value, and it is treated as the value of

; The second value must be one of the following:

  • A unitless number (<number>), it will be taken as<flex-shrink>The value of the
  • A valid width (width) value, which will be treated as<flex-basis>The value of the

Ternary syntax:

  • The first value must be a unitless number (<number>), and it will be taken as<flex-grow>The value of the
  • The second value must be a unitless number (<number>), and it will be taken as<flex-shrink>The value of the
  • The third value must be a valid width (width) value, and it will be treated as<flex-basis>The value of the

The Flex property can be:

  • auto: Flex projects will work on their ownwidthheightTo determine the size, but Flex projects scale according to the amount of space left in the Flex container. It is equivalent toflex: 1 1 auto
  • initial: Flex projects will work on their ownwidthheightTo set the size. It will shorten itself to fit the Flex container, but it will not elongate and absorb the extra space left in the Flex container to fit the Flex container. It is equivalent toflex: 0 1 auto
  • none: Flex projects will work on their ownwidthheightTo set the size. It is completely inelastic (it neither shortens nor elongates to fit the Flex container). It is equivalent toflex: 0 0 auto
  • <flex-grow>: defines the Flex projectflex-growAttribute. The value is<number>
  • <flex-shrink>: defines the Flex projectflex-shrinkAttribute. The value is<number>
  • <flex-basis>: defines the Flex projectflex-basisProperties.If the value is0, units must be added so as not to be regarded as scalability

flex-growTo calculate

Flex-grow calculation formula:


Example:

Suppose there are four Flex projects in the Flex container with the following parameters:

  • The Flex container width is80vw
  • There are four Flex projects in the Flex container, and each Flex project has a width of10vw
  • Flex project widths sum to10vw x 4 = 40vw
  • The remaining space of the Flex container is80vw - 40vw = 40vw
  • The Flex projectflex-growThe values of are respectively0123For all Flex projectsflex-growSum to0 plus 1 plus 2 plus 3 is 6
flex-growThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-grow 0 1 2 3 0 plus 1 plus 2 plus 3 is 6
Flex project width 10vw 10vw 10vw 10vw 10vw x 4 = 40vw
Flex container width 80vw
Flex container free space 80vw – 40vw = 40vw
Flex project new width ? ? ? ?

Calculation process:


The calculated results:

flex-growThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-grow 0 1 2 3 0 plus 1 plus 2 plus 3 is 6
Flex project width 10vw 10vw 10vw 10vw 10vw x 4 = 40vw
Flex container width 80vw
Flex container free space 80vw – 40vw = 40vw
Flex project new width 10vw 16.667 vw 23.333 vw 30vw

Flex-grow can also take on small values. If you change the values of flex-grow in the above example to 0, 0.1, 0.2, and 0.3, the total flex-grow (flex-grow and for all Flex projects) is 0.6, which is less than 1. At this point, the Flex project will also divide up the remaining space of the Flex container based on the Flex-grow factor. The Flex will also grow larger, but the remaining space of the Flex container will not be completely divided up because all flex-grow sums are less than 1. In this example, only 60% of the remaining Flex container width is split up.

If the flex-grow sum is less than 1, the formula is as follows:


flex-growThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-grow 0 1. 2. 3. 0 + 1 + 2+ 3 =.6
Flex project width 10vw 10vw 10vw 10vw 10vw x 4 = 40vw
Flex container width 80vw
Flex container free space 80vw – 40vw = 40vw
Flex project new width 10vw 14vw 18vw 22vw

Even if the flex-grow sum of all Flex projects in a Flex container is greater than 1, it is not absolutely safe to say that Flex projects can divide up the remaining space in a Flex container based on their percentage of Flex-grow. Because the size of the element is affected by max-width. When a Flex project explicitly sets the value of max-width, the Flex project uses the value of max-width when the Flex project calculates a width greater than the value of max-width. For example, in the previous example, we set the value of max-width to 18vw for all Flex projects, and the calculation process and result are as follows:

flex-growThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-grow 0 1 2 3 0 plus 1 plus 2 plus 3 is 6
Flex project width 10vw 10vw 10vw 10vw 10vw x 4 = 40vw
Flex container width 80vw
Flex container free space 80vw – 40vw = 40vw
The new width calculated by the Flex project 10vw 16.667 vw 23.333 vw 30vw
The Flex project sets the maximum width 18vw 18vw 18vw 18vw
Flex project final width 10vw 16.667 vw 18vw 18vw

At this time, the remaining Flex container space is not used up, 40VW-0VW-6.667 VW-8VW-8vw = 17.333 VW, that is, the Flex container has 17.333 VW remaining space.

If a Flex project does not explicitly set width-related properties (including flex-basis), then when flex-grow is evaluated, the Flex project is evaluated by the width of its content.


It can be obtained from the figure above:

  • The Flex container width is804px
  • The width of the Flex project is43.36 px.92.09 px.140.83 px.189.56 px., the sum of all Flex project widths is465.84 px.
  • The remaining width of the Flex container is804px-465.84px = 338.16px
  • For all Flex projectsflex-growA value of1, for all Flex projectsflex-growSum to4

Apply the corresponding values to the flex-grow formula to obtain:

flex-growThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-grow 1 1 1 1 1 x 4 = 4
Flex project width 43.36 px. 92.09 px. 148.83 px. 189.56 px. 465.84 px.
Flex container width 804px
Flex container free space 338.16 px.
Flex project new width 127.9 px. 176.63 px. 225.37 px. 274.1 px.

Note that different browsers treat decimals differently.

flex-shrinkTo calculate

Flex-shrink calculation formula:


Example:

Suppose the Flex container has four Flex projects with the following parameters:

  • The Flex container width is40vw
  • There are four Flex projects in the Flex container, and each Flex project has a width of15vw
  • Flex project widths sum to15vw x 4 = 60vw
  • The insufficient space of the Flex container is40vw - 60vw = -20vw
  • The Flex projectflex-shrinkThe values of are respectively0123For all Flex projectsflex-shrinkSum to0 plus 1 plus 2 plus 3 is 6
flex-shrinkThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-shrink 0 1 2 3 0 plus 1 plus 2 plus 3 is 6
Flex project width 15vw 15vw 15vw 15vw 15vw x 4 = 60vw
Flex container width 40vw
The Flex container is out of space 60vw – 40vw = 20vw
Flex project new width ? ? ? ?

Calculation process:


The calculated results:

flex-shrinkThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-shrink 0 1 2 3 0 plus 1 plus 2 plus 3 is 6
Flex project width 15vw 15vw 15vw 15vw 15vw x 4 = 60vw
Flex container width 40vw
The Flex container is out of space 60vw – 40vw = 20vw
Flex project shrinkage ratio 0 0.1667 0.333 0.5
Flex project new width 15vw 11.67 vw 8.33 vw 5vw

There is even another formula for calculating flex-shrink:


Flex-shrink is similar to flex-grow, and it can also be a small value. If the sum of Flex-shrink for all Flex projects in a Flex container is less than 1, then the Flex container’s insufficient space will not be divided up by the Flex project according to the shrink factor, and the Flex project will still overflow the Flex container.

If the flex-shrink sum is less than 1, the formula is as follows:


Based on the above example, setting flex-shrink to 0, 0.1, 0.2, and 0.3 for a Flex project is calculated as follows:

flex-shrinkThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-shrink 0 0.1 0.2 0.3 0.6
Flex project width 15vw 15vw 15vw 15vw 15vw x 4 = 60vw
Flex container width 40vw
The Flex container is out of space 60vw – 40vw = 20vw
Flex project new width 15vw 13vw 11vw 9vw

Even if the flex-shrink sum of all Flex projects in a Flex container is greater than 1, it is not absolutely safe to say that a Flex project can divide up the insufficient space in a Flex container according to its own flex-shrink percentage. Because the size of the element is affected by the min-width. When a Flex project explicitly sets the value of min-width, the Flex project will use the min-width value if the Flex project calculates a width smaller than min-width based on Flex shrink. For example, in the previous example, we set a min-width value of 10vw for all Flex projects, and the calculation is as follows:

flex-shrinkThe name of the variable in the formula Flex1 Flex2 Flex3 Flex4 The total number of
The Flex projectflex-shrink 0 1 2 3 0 plus 1 plus 2 plus 3 is 6
Flex project width 15vw 15vw 15vw 15vw 15vw x 4 = 60vw
Flex container width 40vw
The Flex container is out of space 60vw – 40vw = 20vw
Flex project shrinkage ratio 0 0.1667 0.333 0.5
The Flex project sets the minimum width 10vw 10vw 10vw 10vw
The new width calculated by the Flex project 15vw 11.67 vw 8.33 vw 5vw
Flex project final width 15vw 11.67 vw 10vw 10vw

In this case, the Flex project’s final width sum will still be greater than the Flex container width, and the Flex project will also overflow the Flex container.

Flex-shrink and Flex-grow are also similar in that when a Flex project in a Flex container is not explicitly set to a width-related property, the initial width of the Flex project is calculated based on the width of its contents.

Flex-shrink is different from Flex-grow in that if a Flex project’s new width calculated according to Flex-shrink approaches 0, the Flex project will set the width according to the min-content of the element. This width will be transferred to other Flex projects and then shrunk by the appropriate shrink factor.

For example, we changed the flex-shrink value for the fourth Flex project from 3 to 9. According to the formula provided above, the new width of Flex item 4 is equal to 15VW – (20VW ÷ 12) × 9 = 0

The computed width is 0, but in fact the rendered width is the min-content of the project (in this case, the width of the “shrink” word, as shown below), which is about 47.95px (about 3.66 VW). This value will then be split into three parts (since flex-shrink is 0, 1, and 2 for the other three Flex projects in this example), and the corresponding Flex project will continue to allocate the width that Flex Project 4 should shrink. That is:

  • Flex Project 1 new width equals15VW-20 ÷ 12 × 0-3.66 ÷ 3 × 0 = 15vw(about196.5 px. )
  • Flex Project 2 new width is equal to15VW-20 ÷ 12 × 1-3.66 ÷ 3 × 1 = 12.113vw(about158.6847 px. )
  • Flex Project 3 new width is equal to15VW-20 ÷ 12 × 2-3.66 ÷ 3 × 2 = 9.227vw(about120.869 px. )

The browser window width at 1310px renders the following:


In the Flexbox layout module, based on the previously mentioned alignment properties of Flex containers, flex-shrink and Flex-grow in Flex projects, we can handle the remaining space and insufficient space in Flex containers very well:

  • The Flex container has free space (the sum of the widths of all Flex items is less than the width of the Flex container) if setflex-grow, the Flex project allocates Flex container space based on the extension factor; In is not setflex-grow, whether alignment is set in the Flex container, if so, Flex container remaining space will be allocated according to alignment, if not, Flex container remaining space remains unchanged
  • The Flex container has insufficient space (the sum of the widths of all Flex items is greater than the width of the Flex container) if setflex-shrinkA value of0, Flex projects do not shrink, Flex projects overflow Flex containers; If not explicitly setflex-shrinkValue, Flex project points evenly allocate Flex container space, Flex project will narrow (Flex projectflex-shrinkThe default value of1), if explicitly setflex-shrinkThe value is not0The Flex project allocates insufficient Flex container space according to a different shrink factor, and the Flex project also gets narrower

Specifically, we can draw a flow chart of this aspect:


flex-basisTo calculate

The calculation of flex-basis is a little more complicated than flex-grow and Flex-shrink because it is related to the Content, width, min-width, and max-width of the Flex project. The relationship here refers to the weight relationship between them. In short, when these attributes appear together in a Flex project, who ultimately determines the width of the Flex project.

In the Flexbox layout, flex-basis can be used to instantiate flex project dimensions, that is, before any Flex container space allocation (surplus or insufficient space) occurs.

In fact, there is an implicit formula for setting the size of a Flex project in the Flexbox layout module:

Content ➜ width ➜ flex-basis

Simply put, if the Flex project does not explicitly specify a value for flex-basis, then flex-basis falls back to the width (or inline-size) property; If the value of the width (or inline-size) attribute is not explicitly specified, flex-basis falls back to calculating the width based on the flex project content. However, determining the size of a Flex project is also influenced by flex-grow and Flex-shrink, as well as the size of the Flex container. The final size of a Flex project is limited by the min-width, max-width(or min-inline-size, max-inline-size) attribute. This has to be paid attention to.

Take a look at an example:

<div class="flex__container">
    <div class="flex__item"></div>
    <div class="flex__item"></div>
    <div class="flex__item"></div>
    <div class="flex__item"></div>
</div>
Copy the code
.flex__container {
    width: 600px;
    display: flex;

    border: 1px dashed #f36;
    align-items: stretch;
}
Copy the code

Flex projects do not explicitly set any properties related to size; use content to support Flex projects.

<div class="flex__container">
    <div class="flex__item">Lorem ipsum dolor sit amet</div>
    <div class="flex__item">Lorem ipsum dolor sit amet consectetur adipisicing elit</div>
    <div class="flex__item">Fugiat dolor nihil saepe. Nobis nihil minus similique hic quas mollitia.</div>
    <div class="flex__item">Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias consequuntur sequi suscipit iure fuga ea!</div>
</div>
Copy the code

In this example, instead of explicitly setting the flex-basis property to the Flex project, the default value auto is used:


Explicitly set the Flex projectwidthValue.

:root{-width: 120px; 
} 

.flex__item { 
  width: var(--width); 
}
Copy the code

All Flex projects are of the same width:


The browser calculates the Flex-basis value as auto, but explicitly sets width: 120px. The final value of the width property determines the size of the Flex project.

Explicitly set a Flex-basis value to a Flex project, that is, a Flex project has both width and flex-basis values.

:root{-width: 120px;
    --flexBasis: 150px;
}

.flex__container {
    width: 800px;
}

.flex__item {
    width: var(--width);
    flex-basis: var(--flexBasis);
}
Copy the code

Although both width and Flex-basis are explicitly set in the Flex project, the final size of the Flex project uses flex-basis values:


The impact on Flex project size in the Flexbox layout module should be judged by its implicit formula (i.e., content ➜ width ➜ Flex-basis). If you want to explicitly size a Flex project, it is best to use flex-basis rather than width (or inline-size).

Finally, don’t forget:

When using flex-basis, it is limited by min-width and max-width (or min-inline-size or max-inline-size in the logical attribute).

In CSS, if an element has both width, min-width, and max-width attributes, its weight calculation follows the following rules:

  • Elements of thewidthIs greater thanmax-widthWhen, of the elementswidthIs equal to themax-width, i.e.,max-widthCan be coveredwidthmax-widthwin)
  • Elements of thewidthLess thanmin-widthWhen, of the elementswidthIs equal to themin-width, i.e.,min-widthCan be coveredwidthmin-widthwin)
  • whenmin-widthIs greater thanmax-widthWhen,min-widthPriority will be higher thanmax-widthmin-widthwin)

If a Flex project has width, flex-basis, and min-width at the same time, the calculation process is as follows:

  • According to the law:content  ➜ width  ➜ flex-basis, determine the value shipped for the Flex project, i.eflex-basisWill be used in Flex projects (flex-basiswin)
  • Then follow the rule: Flex projectwidthLess thanmin-widthWhen the Flex projectwidthIs equal to themin-width, i.e.,min-widthCan be coveredwidth(* *min-widthWin * *)

This way, if flex-basis is smaller than min-width, the flex project’s width will be min-width, meaning that min-width overwrites flex-basis (min-width wins).

If a Flex project contains both width, flex-basis, and max-width, the calculation is as follows:

  • According to the law:content  ➜ width  ➜ flex-basis, determine the value shipped for the Flex project, i.eflex-basisWill be used in Flex projects (flex-basiswin)
  • Then follow the rule: Flex projectwidthIs greater thanmax-widthWhen the Flex projectwidthIs equal to themax-width, i.e.,max-widthCan be coveredwidthmax-widthwin)

This way, if flex-basis is larger than max-width, the flex project width will be max-width, i.e., max-width overrides flex-basis (max-width wins).

If a Flex project has width, flex-basis, min-width, and max-width at the same time, a new rule will be added to the above rule to determine:

  • When min-width is greater than max-width, min-width has a higher priority than max-width.

So apply to the Flex project:

  • flex-basisIs greater thanmax-width, the Flex project width is equal tomax-width, i.e.,max-widthCan be coveredflex-basismax-widthwin)
  • flex-basisLess thanmin-width, the Flex project width will take the valuemin-width, i.e.,min-widthcoverflex-basis(* *min-widthWin * *)

** flex-basis = min-width ** flex-basis = min-width ** flex-basis = min-width ** flex-basis = min-width Conversely, if min-width is smaller than max-width, then max-width ** is used if flex-basis is larger than max-width.

If you understand, you can use simpler rules to determine the size to use for Flex projects.

First of all, according to thecontent  ➜ width  ➜ flex-basisTo decide which to use for the Flex project. If the Flex project is explicitly setflex-basisProperty is ignoredcontentwidth. andmin-widthIs used to set the lower limit of the Flex project;max-widthIs used to set the upper limit of a Flex project.

Use a simple flow chart to describe:


Note that flex-shrink and flex-grow on Flex projects also affect the size of Flex projects!

On the Flex projectmargin

Margin = auto; margin = auto; margin = auto; margin = auto


For an effect like the one below, using margin-left: auto is very useful:


Case finishing

Padding with automatic width issues


For this case, the better scheme does not explicitly set any padding and margin attributes for the inner elements. A manual implementation might look like this:

<div class="flex__container">
  <span class="coupon">volume</span>
  <span class="divider"></span>
  <span class="price">&yen;1000</span>
</div>
Copy the code
.flex__container {
  display: inline-flex;
  min-width: 200px;
  height: 60px;
  
  border: 1px solid rgba(255.0.54.1);
  background-color: rgba(255.0.54.0.1);
  border-radius: 4px;
  color: #ff0036;
  font-size: 24px;
  font-weight: 400;
}

.flex__container > span {
  display: inline-flex;
  justify-content: center;
  align-items: center;
}

.divider {
  border-right: 1px dashed currentColor;
}

.coupon {
  min-width: 50px;
}

.price {
  flex: 1;
  min-width: 0;
  padding: 0 10px;
}
Copy the code


  • ① Like Button, Badge, etc. (shape looks similar to inline block), set the Flex container toinline-flexAnd set it to onemin-width(equivalent to Sketch by default) and oneheight
  • ② From the analysis of the design draft, the width of the front “volume” is known, set a fixed width on the elementwidth
  • (3) a covenant1pxThe secant line can be usedborderOr fixed widthwidth
  • ④ The “price” on the right is the next undetermined factor, which can be set explicitly on Flex projectsflex: 1, allowing this section to occupy the remaining space of the Flex container
  • ⑤ In order to make “price” more extensible, when the value is extended to the Flex container with no space left, the number will be next to the Flex container spindle end and the dividing line, in order to make the visual friendly, to set one in “price” containerpadding-leftpadding-right

summary

This note covers most of the Flexbox specification and some of the critical points in using Flexbox for UI layout beyond the basics and details mentioned in this article. Examples include positioning in Flex containers, hierarchical computation, Flex containers and Flex projects running into Overflow, and scrolling computation in Flex containers. These are too prescriptive for the scene and too complex to handle the boundaries. In our daily use of Flexbox there is little or no encounter. Therefore, it is not listed in the article.

If you’re using Flexbox, and specifically imgCook’s autorestore UI, and it doesn’t work the way you expected, or if anything doesn’t make sense, feel free to poke around.



Tao department front – F-X-team opened a weibo!
In addition to the article there is more team content to unlock 🔓