Flex html examples. The Complete Guide to Flexbox

  • Translation

about the author: Rachel Andrew is not only the editor-in-chief of Smashing Magazine, but also a web developer, writer and speaker. She is the author of a number of books, including The New CSS Layout, one of the developers of the Perch content management system. Writes about business and technology on his website rachelandrew.co.uk.

Summary: In this article, we'll look at the alignment properties in Flexbox and some basic rules on how alignment along the main and cross axis works.

Values ​​work the same way vertically, that is, if flex-direction is applied to column . True, you may not have free space in the column for distribution if you do not add a height or block-size to the container, as in this demo.

Axis alignment using align-content

If the container has multiple axes and flex-wrap: wrap is specified, then align-content can be used to align the rows on the cross axis. But additional space is required. In this demo, the cross axis is running in the column direction, and I have specified the height of the container to be 60vh. Since this is more than is necessary to display all the elements, there is free vertical space.

I can then apply align-content with any of the .

If the flex-direction is column , then align-content works as in the following example.

As with justify-content , we work with a group of rows and allocate free space.

Property by place-content

In the Box Alignment specification you can find the place-content property. Using this property means that you are setting justify-content and align-content at the same time. The first value is for align-content , the second is for justify-content . If only one value is specified, it applies to both properties:

Container ( place-content: space-between stretch; )
Corresponds to this:

Container ( align-content: space-between; justify-content: stretch; )
And this code:

Container ( place-content: space-between; )
Equivalent to the following:

Container ( align-content: space-between; justify-content: space-between; )

Axis alignment using align-items

Now we know that we can align a set of elements or rows as a group. However, there is another way to align elements relative to each other on a transverse axis. A container has a height, which is determined by the height of the tallest element.


Alternatively, it can be defined by the height property in the container:


Why elements are stretched to the size of the tallest element is because the initial value of the align-items parameter is stretch . The elements are stretched along the transverse axis to the size of the container in that direction.

Note that in a multi-line container, each line acts as a new container. The tallest element in that row will determine the size of all elements in that row.

In addition to the starting value stretch , you can set align-items to flex-start , in which case they are aligned to the start of the container and no longer stretch in height.


The flex-end value moves them to the end of the container along the cross axis.


If you use the value center , then the elements are centered relative to each other:


We can also align them to the baseline. This ensures that the text is aligned to the same base, as opposed to aligning the margins around the text.


All these options can be tried in demo.

Custom alignment with align-self

The align-items property specifies the alignment of all elements at once. In effect, it sets the align-self values ​​for all elements of the group. You can also use the align-self property on any single element to align it within a line and relative to other elements.

The following example uses align-items in the container to center the entire group, but also align-self for the first and last elements.

Why isn't there justify-self ?

The question often arises as to why it is not possible to align one element or group of elements along a major axis. Why doesn't Flexbox have a -self property for major axis alignment? If you think of justify-content and align-content as a way to allocate space, the answer becomes more obvious. We deal with elements as a group and place free space in a certain way: either at the beginning or end of the group, or between elements.

It might also be helpful to think about how justify-content and align-content work in CSS Grid Layout. In Grid, these properties are used to allocate free space in the grid container. between grid tracks. Here, too, we take a group of tracks - and using these properties we distribute free space between them. Since we operate in a group in both Grid and Flexbox, we cannot take a single element and do something different with it. However, there is a way to get the layout design that layout designers want when they talk about the self property on the main axis. This is the use of automatic fields.

Using Auto Margins on the Primary Axis

If you've ever centered a block in CSS (for example, a wrapper for homepage content by setting the left and right margins to auto), then you already have some experience with automatic margins. A value of auto for margins fills as much space as possible in the specified direction. To center the block, we set both the left and right margins to auto: they each try to take up as much space as possible, and therefore place our block in the center.

Automatic margins work very well in Flexbox for aligning individual elements or groups of elements on the main axis. The following example shows a typical case. There is a navigation bar, the items are displayed as a string and use the initial value justify-content: start . I want the last item to appear separately from the others at the end of the line - provided there is enough space in the line for this to happen.

We take this element and set the margin-left property to auto . This means that the box tries to get as much space to the left of the element as possible, meaning the element is pushed to the right edge.

If you use automatic margins on the main axis, then justify-content will no longer have effect because the automatic margins will take up all the space that would otherwise be allocated using justify-content .

Spare alignment

For each alignment method, a fallback is described - what will happen if the specified alignment is not possible. For example, if you only have one element in a container, and you specify justify-content: space-between , what should happen? In this case, the flex-start fallback alignment is applied - one element will be aligned at the start of the container. In the case of justify-content: space-around, the fallback alignment is center .

In the current specification you cannot change the fallback alignment. There is a specification note that allows for the possibility of specifying an arbitrary fallback in future versions.

Safe and Unsafe Alignment

A recent addition to the Box Alignment specification is the concept of safe and unsafe alignment using keywords safe And unsafe.

In the following code, the last element is too wide for the container, and with an unsafe alignment and a flex container on the left side of the page, the element is cut off because the overflow extends beyond the page's boundaries.

Container ( display: flex; flex-direction: column; width: 100px; align-items: unsafe center; ) .item:last-child ( width: 200px; )


Secure alignment prevents data loss by moving the overflow to the other side.

Container ( display: flex; flex-direction: column; width: 100px; align-items: safe center; ) .item:last-child ( width: 200px; )


These keywords are not yet supported by all browsers, but demonstrate how the Box Alignment specifications add control to Flexbox.

Conclusion

Alignment properties started out as a list in Flexbox, but now have their own specification and apply to other layout contexts. Here are a few key facts to help you remember their use in Flexbox:
  • justify - for the main axes, and align - for the transverse ones;
  • align-content and justify-content require free space;
  • the align-content and justify-content properties are applied to the elements in the group, distributing space between them. You cannot specify the alignment of an individual element because the -self property is missing;
  • if you want to align one element or split a group along the main axis, use automatic fields;
  • align-items sets the same align-self properties for the entire group. Use align-self on a child element of a group to set its value individually.

Tags: Add tags

Flexbox (Flexible Box Layout Module) Specification is a method of positioning elements in horizontal or vertical directions.

Flexbox combines a set of properties for a parent flex container and for child flex items.

For an element to become a flex container, it must be assigned display: flex; or display: inline-flex;(block or line respectively).

Two axes are created inside the flex container: the main one and the transverse axes perpendicular to it. First, flex elements are aligned along the main axis, and then along the transverse one.

Flex container properties

flex-direction Defines the direction of the main axis. Possible values:
  • row– from left to right (default);
  • row-reverse- from right to left;
  • column- top down;
  • column-reverse- down up.
flex-wrap Determines whether the container is multi-line. Possible values:
  • nowrap– flex elements are lined up in one line; if they do not fit into the container, they go beyond its boundaries (by default);
  • wrap– flex elements are lined up in several lines if they do not fit into one;
  • wrap-reverse- similar to wrap, but the transfer occurs from bottom to top.
flex-flow Defines two parameters at once: flex-direction and flex-wrap.
For example, flex-flow: column wrap;
justify-content Determines the alignment of elements along the major axis. Possible values:
  • flex-start– flex elements are pressed to the beginning of the main axis (by default);
  • flex-end– flex elements are pressed against the end of the main axis;
  • center– flex elements are aligned to the center of the main axis;
  • space-between– flex elements are distributed along the main axis, with the first element pressed to the beginning of the axis, and the last one to the end;
  • space-around– flex elements are distributed along the main axis, with free space divided equally between the elements. But it's worth noting that the spaces add up and the distance between elements is twice as large as the distance between the edges of the container and the outermost elements.
align-items Determines the alignment of elements along the transverse axis. Possible values:
  • flex-start– flex elements are pressed to the beginning of the transverse axis (by default);
  • flex-end– flex elements are pressed against the end of the transverse axis;
  • center– flex elements are aligned to the center of the transverse axis;
  • baseline– flex elements are aligned along their baseline. The base line is an imaginary line running along the bottom edge of the characters without taking into account overhangs, such as those of the letters “d”, “r”, “ts”, “sch”;
  • stretch– flex elements stretch, taking up all the available space along the transverse axis. But if the elements have a given height, then stretch will be ignored.
align-content Determines the cross-axis alignment of entire rows of flex items. Possible values:
  • flex-start– rows of flex elements are pressed to the beginning of the transverse axis (by default);
  • flex-end– rows of flex elements are pressed against the end of the transverse axis;
  • center– rows of flex elements are aligned to the center of the transverse axis;
  • space-between– rows of flex elements are distributed along the transverse axis, with the first row pressed to the beginning of the axis, and the last one to the end;
  • space-around– rows of flex elements are distributed along the transverse axis, with free space divided equally between the rows. But it is worth noting that the spaces add up and the distance between the lines is twice as large as the distance between the edges of the container and the outermost lines.
  • stretch– rows of flex elements are stretched, taking up all the available space along the transverse axis. But if the elements have a given height, then stretch will be ignored.

This property does not work for a single line flex container.


Flex Element Properties

order Determines the order in which a single flex element appears within a flex container. Specified as an integer. The default is 0, then the elements follow each other in a natural flow order. Meaning order specifies the weight of the element's position in the sequence, rather than its absolute position.
flex-basis Defines the base size of a flex item before allocating space within the container. Can be specified in px, %, em and other units of measurement. Essentially, this is a kind of starting point relative to which the element is stretched or compressed. Default value – auto, with the size of the element depending on the size of the internal content.
flex-grow Determines how much free space inside the container the flex item will add to its base size. Specified by an integer that serves as a proportion. The default is 0. If all elements flex-grow: 1, then they will all be the same size. If you set one flex item to 2, it will add twice as much to its base size as the others.
flex-shrink Determines how much, if there is not enough space, the flex element will shrink relative to the reduction of neighboring elements inside the flex container. Specified by an integer that serves as a proportion. The default is 1. If one flex element is set to flex-shrink: 2, then twice as much will be subtracted from its base size as from others if the container is smaller than the sum of the base sizes of the elements it contains.
flex Defines three parameters at once: flex-grow, flex-shrink, flex-basis.
For example, flex: 1 1 200px;
align-self Overrides the default alignment or align-items, for a specific flex element. Possible values:
  • flex-start– the flex element is pressed to the beginning of the transverse axis (by default);
  • flex-end– the flex element is pressed against the end of the transverse axis;
  • center– the flex element is aligned to the center of the transverse axis;
  • baseline– the flex element is aligned to the baseline;
  • stretch– flex elements are stretched, taking up all the available space along the transverse axis. But if the height is given, then stretch will be ignored.

Features of using Flexbox in practice

1. Right alignment

Flexbox can rightfully be called a successful attempt to solve a huge range of problems when building layouts in CSS. But before we move on to its description, let's find out what's wrong with the layout methods we use now?

Any layout designer knows several ways to align something vertically or make a 3-column layout with a rubbery middle column. But let's admit that all these methods are quite strange, look like a hack, are not suitable in all cases, are difficult to understand and do not work if certain magical conditions that have developed historically are not met.

This happened because html and css developed evolutionarily. At the beginning, web pages looked like single-threaded text documents, a little later, breaking the page into blocks was done with tables, then it became fashionable to layout with floats, and after the official death of ie6, inline-block techniques were also added. As a result, we inherited an explosive mixture of all these techniques, used to build layouts for 99.9% of all existing web pages.

Multi-line organization of blocks inside a flex container.

flex-wrap

All the examples that we gave above were built taking into account the single-line (single-column) arrangement of blocks. It must be said that by default, a flex container will always arrange the blocks inside itself in one line. However, the specification also supports multiline mode. The flex-wrap CSS property is responsible for multi-line content inside a flex container.

Available values flex-wrap:

  • nowrap (default value): blocks are arranged in one line from left to right (in rtl from right to left)
  • wrap: blocks are arranged in several horizontal rows (if they do not fit in one row). They follow each other from left to right (in rtl from right to left)
  • wrap-reverse: same as wrap, but the blocks are arranged in the reverse order.

flex-flow is a convenient shorthand for flex-direction + flex-wrap

In essence, flex-flow provides the ability to describe the direction of the main and multi-line transverse axis in one property. Default flex-flow: row nowrap .

flex-flow:<‘flex-direction’> || <‘flex-wrap’>

CSS

/* i.e. ... */ .my-flex-block( flex-direcrion:column; flex-wrap: wrap; ) /* this is the same as... */ .my-flex-block( flex-flow: column wrap; )

align-content

There is also an align-content property, which determines how the resulting rows of blocks will be vertically aligned and how they will divide the entire space of the flex container.

Important: align-content only works in multi-line mode (i.e. in the case of flex-wrap:wrap; or flex-wrap:wrap-reverse;)

Available values align-content:

  • flex-start: rows of blocks are pressed to the beginning of the flex container.
  • flex-end: rows of blocks are pressed to the end of the flex container
  • center: rows of blocks are in the center of the flex container
  • space-between: the first row of blocks is located at the beginning of the flex container, the last row of blocks is at the end, all other rows are evenly distributed in the remaining space.
  • space-around: rows of blocks are evenly distributed from the beginning to the end of the flex container, dividing all available space equally.
  • stretch (default value): The rows of blocks are stretched out to take up all the available space.

The CSS properties flex-wrap and align-content should be applied directly to the flex container, not to its children.

Demo of multi-line properties in flex

CSS rules for child elements of a flex container (flex blocks)

flex-basis – the basic size of a single flex block

Sets the initial major axis size for a flex block before transformations based on other flex factors are applied to it. Can be specified in any length units (px, em, %, ...) or auto (default). If set as auto, the block dimensions (width, height) are taken as a basis, which, in turn, can depend on the size of the content, if not specified explicitly.

flex-grow – “greed” of a single flex block

Determines how much larger an individual flex block can be than adjacent elements, if necessary. flex-grow accepts a dimensionless value (default 0)

Example 1:

  • If all flex boxes inside a flex container have flex-grow:1 then they will be the same size
  • If one of them has flex-grow:2 then it will be 2 times larger than all the others

Example 2:

  • If all flex boxes inside a flex container have flex-grow:3 then they will be the same size
  • If one of them has flex-grow:12 then it will be 4 times larger than all the others

That is, the absolute value of flex-grow does not determine the exact width. It determines its degree of “greediness” in relation to other flex blocks of the same level.

flex-shrink – the “compressibility” factor of a single flex block

Determines how much the flex block will shrink relative to adjacent elements inside the flex container if there is not enough free space. Defaults to 1.

flex – shorthand for the flex-grow, flex-shrink and flex-basis properties

flex: none | [<"flex-grow"> <"flex-shrink">? || <"flex-basis"> ]

CSS

/* i.e. ... */ .my-flex-block( flex-grow:12; flex-shrink:3; flex basis: 30em; ) /* this is the same as... */ .my-flex-block( flex: 12 3 30em; )

Demo for flex-grow, flex-shrink and flex-basis

align-self – alignment of a single flex block along the transverse axis.

Makes it possible to override the flex container's align-items property for an individual flex block.

Available align-self values ​​(same 5 options as align-items)

  • flex-start: the flex block is pressed to the beginning of the transverse axis
  • flex-end: the flex block is pressed against the end of the cross axis
  • center: flex block is located in the center of the cross axis
  • baseline: flex block is aligned to baseline
  • stretch (default value): The flex block is stretched to take up all available space along the cross axis, taking into account min-width / max-width if set.

order – the order of a single flex block inside a flex container.

By default, all blocks will follow each other in the order specified in the html. However, this order can be changed using the order property. It is specified as an integer and defaults to 0.

The order value does not specify the absolute position of the element in the sequence. It determines the weight of the element's position.

HTML

item1
item2
item3
item4
item5

In this case, the blocks will follow one after another along the main axis in the following order: item5, item1, item3, item4, item2

Demo for align-self and order

margin: auto vertically. Dreams Come True!

You can love Flexbox at least because the familiar horizontal alignment via margin:auto works here for verticals too!

My-flex-container ( display: flex; height: 300px; /* Or whatever */ ) .my-flex-block ( width: 100px; /* Or whatever */ height: 100px; /* Or whatever * / margin: auto; /* Magic! The block is centered vertically and horizontally! */ )

Things to Remember

  1. You should not use flexbox where it is not necessary.
  2. Defining regions and changing the order of content in many cases is still useful to make dependent on the page structure. Think it through.
  3. Understand flexbox and know the basics. This makes it much easier to achieve the expected result.
  4. Don't forget about margins. They are taken into account when setting axis alignment. It is also important to remember that margins in flexbox do not “collapse” as they do in a normal flow.
  5. The float value of flex blocks is not taken into account and has no meaning. This can probably somehow be used for graceful degradation when switching to flexbox.
  6. Flexbox is very well suited for the layout of web components and individual parts of web pages, but has not shown its best side when laying out basic layouts (position of article, header, footer, navbar, etc.). This is still a controversial point, but this article shows the shortcomings quite convincingly xanthir.com/blog/b4580

Finally

I think that flexbox, of course, will not supplant all other layout methods, but, of course, in the near future it will occupy a worthy niche in solving a huge number of tasks. And of course, you need to try working with him now. One of the following articles will be devoted to specific examples of working with flex layout. Subscribe to news;)

One of the reasons that flexbox quickly caught the interest of web developers is that it brought proper alignment capabilities to the web for the first time. It enabled proper vertical alignment, so we can at last easily center a box. In this guide, we will take a thorough look at how the alignment and justification properties work in Flexbox.

To center our box we use the align-items property to align our item on the cross axis, which in this case is the block axis running vertically. We use justify-content to align the item on the main axis, which in this case the inline axis running horizontally.

You can take a look at the code of this example below. Change the size of the container or nested element and the nested element always remains centered.

Properties that control alignment

The properties we will look at in this guide are as follows.

  • justify-content - controls alignment of all items on the main axis.
  • align-items - controls alignment of all items on the cross axis.
  • align-self - controls alignment of an individual flex item on the cross axis.
  • align-content - described in the spec as for “packing flex lines”; controls space between flex lines on the cross axis.

We will also discover how auto margins can be used for alignment in flexbox.

Note: The alignment properties in Flexbox have been placed into their own specification - CSS Box Alignment Level 3. It is expected that this spec will ultimately supersede the properties as defined in Flexbox Level One.

The Cross Axis

The align-items and align-self properties control alignment of our flex items on the cross axis, down the columns if flex-direction is row and along the row if flex-direction is column .

We are making use of cross-axis alignment in the most simple flex example. If we add display: flex to a container, the child items all become flex items arranged in a row. They will all stretch to be as tall as the tallest item, as that item is defining the height of the items on the cross axis. If your flex container has a height set, then the items will stretch to that height, regardless of how much content is in the item.

The reason the items become the same height is that the initial value of align-items , the property that controls alignment on the cross axis, is set to stretch .

We can use other values ​​to control how the items align:

  • align-items: flex-start
  • align-items: flex-end
  • align-items: center
  • align-items: stretch
  • align-items: baseline

In the live example below, the value of align-items is stretch . Try the other values ​​and see how all of the items align against each other in the flex container.

Aligning one item with align-self

The align-items property sets the align-self property on all of the flex items as a group. This means you can explicitly declare the align-self property to target a single item. The align-self property accepts all of the same values ​​as align-items plus a value of auto , which will reset the value to that which is defined on the flex container.

In this next live example, the flex container has align-items: flex-start , which means the items are all aligned to the start of the cross axis. I have targeted the first item using a first-child selector and set that item to align-self: stretch ; another item has been selected using its class of selected and given align-self: center . You can change the value of align-items or change the values ​​of align-self on the individual items to see how this works.

Changing the main axis

So far we have looked at the behavior when our flex-direction is row , and while working in a language written top to bottom. This means that the main axis runs along the row horizontally, and our cross axis alignment moves the items up and down.

If we change our flex-direction to column, align-items and align-self will align the items to the left and right.

You can try this out in the example below, which has a flex container with flex-direction: column yet otherwise is exactly the same as the previous example.

Aligning content on the cross axis - the align-content property

So far we have been aligning the items, or an individual item inside the area defined by the flex-container. If you have a wrapped multiple-line flex container then you might also want to use the align-content property to control the distribution of space between the rows. In the specification this is described as packing flex lines.

For align-content to work you need more height in your flex container than is required to display the items. It then works on all the items as a set, and dictates what happens with that free space, and the alignment of the entire set of items within it.

The align-content property takes the following values:

  • align-content: flex-start
  • align-content: flex-end
  • align-content: center
  • align-content: space-between
  • align-content: space-around
  • align-content: stretch
  • align-content: space-evenly (not defined in the Flexbox specification)

In the live example below, the flex container has a height of 400 pixels, which is more than needed to display our items. The value of align-content is space-between , which means that the available space is shared out between the flex lines, which are placed flush with the start and end of the container on the cross axis.

Try out the other values ​​to see how the align-content property works.

Once again we can switch our flex-direction to column in order to see how this property behaves when we are working by column. As before, we need enough space in the cross axis to have some free space after displaying all of the items.

Note: the value space-evenly is not defined in the flexbox specification and is a later addition to the Box Alignment specification. Browser support for this value is not as good as that of the values ​​defined in the flexbox spec.

In short, Flexbox layout gives us simple solutions to once difficult problems. For example, when you need to align an element vertically, or press the footer to the bottom of the screen, or simply insert several blocks in one row so that they occupy all the free space. Similar problems can be solved without flex. But as a rule, these solutions are more like “crutches” - techniques for using CSS for purposes other than their intended purpose. Whereas with flexbox such tasks are solved exactly as the flex model is intended.

CSS Flexible Box Layout Module (CSS module for layouts with flexible blocks), flexbox for short, was created to eliminate the shortcomings when creating a wide variety of HTML designs, including those adapted to different widths and heights, and make the layout logical and simple. And a logical approach, as a rule, works in unexpected places, where the result has not been checked - logic is everything!

Flexbox allows you to elegantly control a variety of parameters of elements inside a container: direction, order, width, height, alignment along and across, distribution of free space, stretching and compression of elements.

Basic knowledge

A FlexBox consists of a Container and its Items (flexible elements).

To enable flexbox, any HTML element just needs to assign the CSS property display:flex; or display:inline-flex; .

1
2

After enabling the flex property, two axes are created inside the container: main and transverse (perpendicular (⊥), cross axis). All nested elements (of the first level) are lined up along the main axis. By default, the main axis is horizontal and directed from left to right (→), and the cross axis is correspondingly vertical and directed from top to bottom (↓).

The main and cross axes can be swapped, then the elements will be located from top to bottom (↓) and when they no longer fit in height, they will move from left to right (→) - that is, the axes simply swapped places. In this case, the beginning and end of the arrangement of the elements does not change - only the directions (axes) change! This is why you need to imagine the axes inside the container. However, one should not think that there are some “physical” axes and they influence something. The axis here is just the direction of movement of the elements inside the container. For example, if we specified the alignment of elements to the center of the main axis and then changed the direction of this main axis, then the alignment will change: the elements were in the middle horizontally, but became in the middle vertically... See the example.

Another important feature of Flexbox is the presence of rows in the transverse direction. To understand what we are talking about, let's imagine that there is a main horizontal axis, there are many elements and they do not “fit” into the container, so they move to another row. Those. a container looks like this: a container with two rows inside it, each row containing several elements. Introduced? Now remember that we can vertically align not only elements, but also rows! How this works is clearly seen in the example for the property. And this is what it looks like schematically:

CSS properties that can affect the layout model: float, clear, vertical-align, columns do not work in flex design. Here a different model for constructing a layout is used and these CSS properties are simply ignored.

Flexbox CSS properties

Flexbox contains different CSS rules to control the entire flex design. Some need to be applied to the main container, and others to the elements of this container.

For container

display:

Enables the flex property for the element. This property covers the element itself and its nested elements: only first-level descendants are affected - they will become elements of the flex container.

  • flex- the element stretches its entire width and has its full space among the surrounding blocks. Line breaks occur at the beginning and end of the block.
  • inline-flex- an element is wrapped around other elements. In this case, its internal part is formatted as a block element, and the element itself is formatted as inline.

flex and inline-flex differ in that they interact differently with surrounding elements, similar to display:block and display:inline-block .

flex-direction:

Changes the direction of the main axis of the container. The transverse axis changes accordingly.

  • row (default)- direction of elements from left to right (→)
  • column- direction of elements from top to bottom (↓)
  • row-reverse- direction of elements from right to left (←)
  • column-reverse- direction of elements from bottom to top ()
flex-wrap:

Controls the transfer of elements that do not fit into the container.

  • nowrap (default)- nested elements are placed in one row (with direction=row) or in one column (with direction=column) regardless of whether they fit into the container or not.
  • wrap- includes moving elements to the next row if they do not fit into the container. This enables the movement of elements along the transverse axis.
  • wrap-reverse- the same as wrap, only the transfer will not be down, but up (in the opposite direction).
flex-flow: direction wrap

Combines both flex-direction and flex-wrap properties. They are often used together, so the flex-flow property was created to help write less code.

flex-flow accepts the values ​​of these two properties, separated by a space. Or you can specify a single value for any property.

/* flex-direction only */ flex-flow: row; flex-flow: row-reverse; flex-flow: column; flex-flow: column-reverse; /* flex-wrap only */ flex-flow: nowrap; flex-flow: wrap; flex-flow: wrap-reverse; /* both values ​​at once: flex-direction and flex-wrap */ flex-flow: row nowrap; flex-flow: column wrap; flex-flow: column-reverse wrap-reverse; justify-content:

Aligns elements along the main axis: if direction=row, then horizontally, and if direction=column, then vertically.

  • flex-start (default)- the elements will go from the beginning (there may be some space left at the end).
  • flex-end- elements are aligned at the end (the space will remain at the beginning)
  • center- in the center (space will remain on the left and right)
  • space-between- the outermost elements are pressed against the edges (the space between the elements is distributed evenly)
  • space-around- free space is evenly distributed between the elements (the outermost elements are not pressed against the edges). The space between the edge of the container and the outer elements will be half as much as the space between the elements in the middle of the row.
  • space-evenly
align-content:

Aligns the rows containing elements along the transverse axis. Same as justify-content only for the opposite axis.

Note: Works when there are at least 2 rows, i.e. If there is only 1 row, nothing will happen.

Those. if flex-direction: row , then this property will align invisible rows vertically. It is important to note here that the height of the block must be set rigidly and must be greater than the height of the rows, otherwise the rows themselves will stretch the container and any alignment of them becomes meaningless, because there is no free space between them... But when flex-direction: column , then the rows move horizontally → and the width of the container is almost always greater than the width of the rows and aligning the rows immediately makes sense...

  • stretch (default)- rows stretch to fill the row completely
  • flex-start- rows are grouped at the top of the container (there may be some space left at the end).
  • flex-end- rows are grouped at the bottom of the container (space will remain at the beginning)
  • center- rows are grouped in the center of the container (space will remain at the edges)
  • space-between- the outer rows are pressed against the edges (the space between the rows is distributed evenly)
  • space-around- free space is evenly distributed between the rows (the outermost elements are not pressed against the edges). The space between the edge of the container and the outer elements will be half as much as the space between the elements in the middle of the row.
  • space-evenly- the same as space-around , only the distance between the outer elements and the edges of the container is the same as between the elements.
align-items:

Aligns elements along a transverse axis within a row (invisible row). Those. The rows themselves are aligned via align-content , and the elements within these rows (rows) are aligned via align-items and all along the transverse axis. There is no such division along the main axis, there is no concept of rows and elements are aligned through justify-content .

  • stretch (default)- elements are stretched to fill the line completely
  • flex-start- elements are pressed to the beginning of the row
  • flex-end- elements are pressed to the end of the row
  • center- elements are aligned to the center of the row
  • baseline- elements are aligned to the text baseline

For container elements

flex-grow:

Sets the element's magnification factor when there is free space in the container. Default flex-grow: 0 i.e. none of the elements should grow and fill the free space in the container.

Default flex-grow: 0

  • If you specify flex-grow:1 for all elements, then they will all stretch equally and fill all the free space in the container.
  • If you specify flex-grow:1 to one of the elements, then it will fill all the free space in the container and alignments via justify-content will no longer work: there is no free space to align...
  • With flex-grow:1 . If one of them has flex-grow:2 then it will be 2 times larger than all the others
  • If all flex boxes inside a flex container have flex-grow:3 then they will be the same size
  • With flex-grow:3 . If one of them has flex-grow:12 then it will be 4 times larger than all the others

How it works? Let's say a container is 500px wide and contains two elements, each with a base width of 100px. This means there are 300 free pixels left in the container. Now, if we specify flex-grow:2; , and the second flex-grow: 1; , then the blocks will occupy the entire available width of the container and the width of the first block will be 300px, and the second 200px. This is explained by the fact that the available 300px of free space in the container was distributed between the elements in a 2:1 ratio, +200px for the first and +100px for the second.

Note: you can specify fractional numbers in the value, for example: 0.5 - flex-grow:0.5

flex-shrink:

Sets the element's reduction factor. The property is the opposite of flex-grow and determines how the element should shrink if there is no free space left in the container. Those. the property starts working when the sum of the sizes of all elements is greater than the size of the container.

Default flex-shrink:1

Let's say the container is 600px wide and contains two elements, each 300px wide - flex-basis:300px; . Those. two elements completely fill the container. Give the first element flex-shrink: 2; , and the second flex-shrink: 1; . Now let's reduce the width of the container by 300px, i.e. elements must shrink by 300px to fit inside the container. They will shrink in a ratio of 2:1, i.e. the first block will shrink by 200px, and the second by 100px and the new element sizes will become 100px and 200px.

Note: you can specify fractional numbers in the value, for example: 0.5 - flex-shrink:0.5

flex-basis:

Sets the base width of the element - the width before other conditions affecting the width of the element are calculated. The value can be specified in px, em, rem, %, vw, vh, etc. The final width will depend on the base width and the values ​​of flex-grow, flex-shrink and the content inside the block. With auto, the element gets a base width relative to the content inside it.

Default: auto

Sometimes it's better to set the width of an element hard through the usual width property. For example, width: 50%; will mean that the element inside the container will be exactly 50%, but the flex-grow and flex-shrink properties will still work. This may be necessary when the element is stretched by the content inside it, more than specified in flex-basis. Example.

flex-basis will be “rigid” if stretch and shrink are set to zero: flex-basis:200px; flex-grow:0; flex-shrink:0; . All this can be written like this: flex:0 0 200px; .

flex: (grow shrink basis)

A short summary of the three properties: flex-grow flex-shrink flex-basis .

Default: flex: 0 1 auto

However, you can specify one or two values:

Flex: none; /* 0 0 auto */ /* number */ flex: 2; /* flex-grow (flex-basis goes to 0) */ /* not a number */ flex: 10em; /* flex-basis: 10em */ flex: 30px; /* flex-basis: 30px */ flex: auto; /* flex-basis: auto */ flex: content; /* flex-basis: content */ flex: 1 30px; /* flex-grow and flex-basis */ flex: 2 2; /* flex-grow and flex-shrink (flex-basis goes to 0) */ flex: 2 2 10%; /* flex-grow and flex-shrink and flex-basis */ align-self:

Allows you to change the align-items property, only for a single element.

Default: from align-items container

  • stretch- the element is stretched to fill the line completely
  • flex-start- the element is pressed to the beginning of the line
  • flex-end- the element is pressed to the end of the line
  • center- the element is aligned to the center of the line
  • baseline- the element is aligned to the text baseline

order:

Allows you to change the order (position, position) of an element in the general row.

Default: order: 0

By default, elements have order: 0 and are placed in the order of their appearance in the HTML code and the direction of the row. But if you change the value of the order property, then the elements will be arranged in the order of values: -1 0 1 2 3 ... . For example, if you specify order: 1 for one of the elements, then all zeros will go first, and then the element with 1.

This way, for example, you can move the first element to the end without changing the direction of movement of the remaining elements or the HTML code.

Notes

What is the difference between flex-basis and width?

Below are the important differences between flex-basis and width/height:

    flex-basis only works for the main axis. This means that with flex-direction:row flex-basis controls the width, and with flex-direction:column controls the height. .

    flex-basis only applies to flex elements. This means that if you disable flex for a container, this property will have no effect.

    Absolute container elements do not participate in flex construction... This means that flex-basis does not affect the flex elements of a container if they are absolute position:absolute . They will need to specify width/height.

  • When using the flex property, 3 values ​​(flex-grow/flex-shrink/flex-basis) can be combined and written briefly, but for width grow or shrink you need to write separately. For example: flex:0 0 50% == width:50%; flex-shrink:0; . Sometimes it's just inconvenient.

If possible, still prefer flex-basis. Use width only when flex-basis is not appropriate.

The difference between flex-basis and width - a bug or a feature?

The content inside a flex element pushes it and cannot go beyond it. However, if you set the width using width or max-width rather than flex-basis , then an element inside a flex container will be able to extend beyond the bounds of that container (sometimes this is exactly the behavior you want). Example:

Flex layout examples

Nowhere in the examples are prefixes used for cross-browser compatibility. I did this for easy reading of the css. Therefore, see the latest versions of Chrome or Firefox for examples.

#1 Simple example with vertical and horizontal alignment

Let's start with the simplest example - vertical and horizontal alignment at the same time and at any block height, even rubber.

Text in the middle

Or like this, without a block inside:

Text in the middle

#1.2 Separation (break) between flex block elements

To position container elements along the edges and randomly select an element after which there will be a break, you need to use the margin-left:auto or margin-right:auto property.

#2 Adaptive menu on flex

Let's create a menu at the very top of the page. On a wide screen it should be on the right. On average, align in the middle. And on the small one, each element must be on a new line.

#3 Adaptive 3 columns

This example shows how to quickly and conveniently make 3 columns, which, when narrowed, will turn into 2 and then into 1.

Please note that this can be done without using media rules, everything is on flex.

1
2
3
4
5
6

Go to jsfiddle.net and change the width of the “result” section

#4 Adaptive blocks on flex

Let's say we need to output 3 blocks, one large and two small. At the same time, it is necessary that the blocks adapt to small screens. We do:

1
2
3

Go to jsfiddle.net and change the width of the “result” section

#5 Gallery with flex and transition

This example shows how quickly you can make a cute accordion with pictures using flex. Pay attention to the transition property for flex.

#6 Flex to Flex (just an example)

The task is to make a flexible block. So that the beginning of the text in each block is on the same line horizontally. Those. As the width narrows, the blocks grow in height. It is necessary that the image is at the top, the button is always at the bottom, and the text in the middle starts along one horizontal line...

To solve this problem, the blocks themselves are stretched with flex and set to the maximum possible width. Each internal block is also a flex structure, with a rotated axis flex-direction:column; and the element in the middle (where the text is) is stretched flex-grow:1; to fill all the free space, this is how the result is achieved - the text began with one line...

More examples

Browser support - 98.3%

Of course, there is no full support, but all modern browsers support flexbox designs. Some still require prefixes. For a real picture, let's look at caniuse.com and see that 96.3% of browsers used today will work without prefixes, with 98.3% using prefixes. This is an excellent indicator to confidently use flexbox.

To know which prefixes are relevant today (June 2019), I will give an example of all flex rules with with the necessary prefixes:

/* Container */ .flex ( display:-webkit-box; display:-ms-flexbox; display:flex; display:-webkit-inline-box; display:-ms-inline-flexbox; display:inline-flex; -webkit-box-orient:vertical; -webkit-box-direction:normal; -ms-flex-direction:column; flex-direction:column; -ms-flex-wrap:wrap; flex-wrap:wrap; -ms -flex-flow:column wrap; flex-flow:column wrap; -webkit-box-pack:justify; -ms-flex-pack:justify; justify-content:space-between; -ms-flex-line-pack: distribute; align-content:space-around; ) /* Elements */ .flex-item ( -webkit-box-flex:1; -ms-flex-positive:1; flex-grow:1; -ms-flex- negative:2; flex-shrink:2; -ms-flex-preferred-size:100px; flex-basis:100px; -ms-flex:1 2 100px; flex:1 2 100px; -ms-flex-item-align :center; align-self:center; -webkit-box-ordinal-group:3; -ms-flex-order:2; order:2; )

It is better if properties with prefixes go before the original property.
This list does not contain any prefixes that are unnecessary today (according to caniuse), but in general there are more prefixes.

Chrome Safari Firefox Opera I.E. Android iOS
20- (old) 3.1+ (old) 2-21 (old) 10 (tweener) 2.1+ (old) 3.2+ (old)
21+ (new) 6.1+ (new) 22+ (new) 12.1+ (new) 11+ (new) 4.4+ (new) 7.1+ (new)
  • (new) - new syntax: display: flex; .
  • (tweener) - old unofficial syntax from 2011: display: flexbox; .
  • (old) - old syntax from 2009: display: box;

Video

Well, don’t forget about the video, sometimes it’s also interesting and understandable. Here are a couple of popular ones:

Useful links on Flex

    flexboxfroggy.com - flexbox educational game.

    Flexplorer is a visual flex code builder.