Flex stretches elements to fit their width. The Complete Guide to Flexbox. Setting flexible dimensions with one property: flex

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 – flex elements are lined up in one line; if they do not fit into the container, they go beyond its boundaries (by default);- similar to
, 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, while 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.
  • Determines the alignment of elements along the major axis. Possible values: align-items
  • – flex elements are pressed to the beginning of the main axis (by default); Determines the alignment of elements along the transverse axis. Possible values:
  • – flex elements are pressed against the end of the main axis;– flex elements are pressed to the beginning of the transverse axis (by default);
  • – flex elements are pressed against the end of the transverse axis;– 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 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”;– flex elements stretch, taking up all the available space along the transverse axis. But if the elements have a given height, then
will be ignored. align-content
  • Determines the alignment of elements along the major axis. Possible values: Determines the cross-axis alignment of entire rows of flex items. Possible values:
  • – flex elements are pressed to the beginning of the main axis (by default);– rows of flex elements are pressed to the beginning of the transverse axis (by default);
  • – flex elements are pressed against the end of the main axis;– rows of flex elements are pressed against the end of the transverse axis;
  • – flex elements are aligned to the center of the main axis;– rows of flex elements are aligned to the center of the transverse axis;
  • – 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;– 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;
  • 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”;– rows of flex elements are distributed along the transverse axis, with free space divided equally between the rows. 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”;– flex elements stretch, taking up all the available space along the transverse axis. But if the elements have a given height, then

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.


– 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

This property does not work for a single line flex container. Flex Element Properties This property does not work for a single line flex container. 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 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 – 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 divided equally between the elements. Overrides the default alignment or
  • Determines the alignment of elements along the major axis. Possible values:, for a specific flex element. Possible values:
  • – flex elements are pressed to the beginning of the main axis (by default);– the flex element is pressed to the beginning of the transverse axis (by default);
  • – flex elements are pressed against the end of the main axis;– the flex element is pressed against the end of the transverse axis;
  • – flex elements are pressed against the end of the transverse axis;– the flex element is aligned to the center of the transverse axis;
  • 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”;– the flex element is aligned to the 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”;– flex elements stretch, taking up all the available space along the transverse axis. But if the elements have a given height, then

– flex elements are stretched, taking up all the available space along the transverse axis. But if the height is given, then

Features of using Flexbox in practice

1. Right alignment The Complete Guide to CSS Flexbox. This complete guide explains everything about flexbox, focusing on everyone possible properties

for the parent element (flex container) and child elements (flex elements). It also includes history, demos, templates, and a browser support table.

Background

flex-flow (Applies to: the parent element of the flex container) Flex container properties This is an abbreviation for - down up. And properties that together define the main and transverse axes of the flex container. The default value is.

row nowrap<‘flex-direction’> || <‘flex-wrap’>

Flex flow:

justify-content

This property determines the alignment along the major axis. It helps distribute the extra remaining free space when all flex items in a row are inflexible, or are flexible but have reached their maximum size. This also provides some control over the alignment of elements when they overflow the line.

  • Determines the alignment of elements along the major axis. Possible values: Container ( justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly | start | end | left | right ... + safe | unsafe; )
  • – flex elements are pressed to the beginning of the main axis (by default);(default): items are shifted to the beginning of the flex-direction direction.
  • : The elements are moved towards the end of the flex direction. start : elements are moved to the beginning writing-mode
  • directions. end : elements are moved to the beginning writing-mode
  • : elements are shifted at the end left Flex container properties: elements are shifted towards the left edge of the container if this doesn't make sense : The elements are moved towards the end of the flex direction..
  • , then he behaves like: elements are shifted towards the right edge of the container if this doesn't make sense Flex container properties: elements are shifted towards the left edge of the container if this doesn't make sense : The elements are moved towards the end of the flex direction..
  • – flex elements are pressed against the end of the main axis;: elements are centered along the line
  • – flex elements are aligned to the center of the main axis;: elements are evenly distributed along the line; the first element is at the beginning of the line, the last element is at the end of the line
  • – 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;: Elements are evenly spaced along a line with equal space around them. Note that visually the spaces are not equal, as all elements have the same space on both sides. The first element will have one unit of space against the edge of the container, but two units of space between the next element, because the next element has its own spacing that is applied.
  • space-evenly: The elements are distributed so that the distance between any two elements (and the distance to the edges) is the same.
Please note that browser support for these values ​​has its own nuances. For example, – flex elements are aligned to the center of the main axis; never got Edge support, and start/end/left/right isn't in Chrome yet. On MDN. The safest values ​​are Determines the alignment of elements along the major axis. Possible values:, – flex elements are pressed to the beginning of the main axis (by default); This is an abbreviation for – flex elements are pressed against the end of the main axis;.

There are also two additional keywords you can associate with these values: safe This is an abbreviation for unsafe. Usage safe ensures that no matter how much you do this type of positioning, you won't be able to position the element so that it appears off-screen (like on top) so that the content can't be scrolled either (this is called "data loss").

align-items


This property defines the default behavior of how flex items are laid out along the cross axis on the current line. Think of it as the justify-content version for the cross axis (perpendicular to the main axis).

Container ( align-items: stretch | flex-start | flex-end | center | baseline | first baseline | last baseline | start | end | self-start | self-end + ... safe | unsafe; )

  • 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”;(default): stretch to fill container (min-width/max-width still respected)
  • Determines the alignment of elements along the major axis. Possible values: / : The elements are moved towards the end of the flex direction. / self-start: elements are placed at the beginning of the transverse axis. The difference between them is small and lies in compliance Flex container properties rules or : elements are moved to the beginning rules
  • – flex elements are pressed to the beginning of the main axis (by default); / directions. / self-end: The elements are located at the end of the transverse axis. The difference is again subtle and lies in compliance Flex container properties or : elements are moved to the beginning rules
  • – flex elements are pressed against the end of the main axis;: elements are centered on the transverse axis
  • – flex elements are pressed against the end of the transverse axis;: elements are aligned to their baseline
safe This is an abbreviation for unsafe Modifier keywords can be used in combination with all of these keywords (although this is not supported by all browsers), this helps prevent elements from being aligned in such a way that the content is inaccessible.

align-content

This property aligns lines within a flex container when there is extra space on the transverse axis, similar to For example, flex-flow: column wrap; Aligns individual elements within a major axis.

Note: This property has no effect when there is only one row of flex items.

Container ( align-content: flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline + ... safe | unsafe; )

  • Determines the alignment of elements along the major axis. Possible values: / : The elements are moved towards the end of the flex direction.: elements moved to the beginning of the container. More supported Determines the alignment of elements along the major axis. Possible values: uses, Flex container properties while : The elements are moved towards the end of the flex direction. uses : elements are moved to the beginning direction.
  • – flex elements are pressed to the beginning of the main axis (by default); / directions.: elements moved to the end of the container. More supported – flex elements are pressed to the beginning of the main axis (by default); uses Flex container properties while directions. uses : elements are moved to the beginning direction.
  • – flex elements are pressed against the end of the main axis;: Elements are centered in the container
  • – flex elements are aligned to the center of the main axis;: elements are evenly distributed; the first line is at the beginning of the container and the last line is at the end
  • – 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;: Elements are evenly spaced with equal space around each row
  • space-evenly: elements are distributed evenly, with equal space around them
  • 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”;(default): lines stretch to fill the remaining space
safe This is an abbreviation for unsafe Modifier keywords can be used in combination with all of these keywords (although this is not supported by all browsers), this helps prevent elements from being aligned in such a way that the content is inaccessible.

Properties for first child elements (flex elements)


order


By default, flex items are arranged in their original order. However, the property This property does not work for a single line flex container. controls the order in which they appear in the flex container.

Item (order: ; /* default is 0 */ )

flex-grow


This property determines the ability of a flex element to stretch when necessary. It takes a value from zero, which serves as a proportion. This is the property of how much available space within a flex container an element should occupy.

If for all elements flex-basis set to 1, the remaining space in the container will be evenly distributed among all child elements. If one of the child elements has a value of 2, that element will take up twice as much space as the others (or try to at least).

Item(flex-grow: ; /* default 0 */ )

flex-shrink

This property determines the ability of a flexible element to compress when necessary.

Item ( flex-shrink: ; /* default 1 */ )
Negative numbers are not supported.

flex-basis

This property specifies the default size of an element before allocating the remaining space. This could be a length (eg 20%, 5rem, etc.) or keyword. Keyword Meaning means "look at my width or height property". Keyword content means "size based on element content" - this keyword is still not very well supported, so it's hard to check what it's used for max-content, min-content or fit-content.

Item ( flex-basis: | auto; /* default auto */ )
If set to 0 , the extra space around the content is not taken into account. If set to Meaning, additional space is distributed depending on its flex-basis meanings.

See this drawing.


flex

This is the shorthand for using flex-basis, Default value – This is an abbreviation for Determines the order in which a single flex element appears within a flex container. together. Second and third parameters ( Default value – This is an abbreviation for Determines the order in which a single flex element appears within a flex container.) are optional. The default is 0 1 Meaning.

Item ( flex: none | [<"flex-grow"> <"flex-shrink">? || <"flex-basis"> ] }
It is recommended to use this shorthand property rather than setting individual properties. This reduction intelligently sets other values.

align-self


This property allows you to override the default alignment (or specified using divided equally between the elements.) for individual flex items.
Please look divided equally between the elements. property to understand the available values.

Item ( align-self: auto | flex-start | flex-end | center | baseline | stretch; )
Please note that properties float, clear This is an abbreviation for vertical-align do not affect flex elements.

Examples

Let's start with very simple example solving an almost daily problem: perfect alignment. The simplest solution for this task is to use flexbox.

Parent ( display: flex; height: 300px; /* Or whatever */ ) .child ( width: 100px; /* Or whatever */ height: 100px; /* Or whatever */ margin: auto; /* Magic ! */ )
This happens due to the fact that the vertical alignment property margin is set to Meaning in a flex container, absorbs additional space. So setting margin to Meaning will make the object perfectly centered on both axes.

Now let's use a few more properties. Consider a list of 6 elements, all with fixed sizes, but there may also be auto-sizes. We want them to be evenly distributed along the horizontal axis so that when the browser size changes, everything scales well and without media queries.

Flex-container ( /* First we create a flex context */ display: flex; /* Then we define a flex-direction and allow elements to wrap onto new lines * Remember that this is the same as: * flex-direction: row; * flex-wrap: wrap; */ flex-flow: row wrap; /* Then we determine how the remaining space is distributed */ justify-content: space-around)
Ready. Everything else is just styling.

If you change the screen resolution or scale, it will look like this:

Let's try something else. Imagine we have right-aligned navigation elements at the top of our website, but we want them to be justified on medium-sized screens and in a single column on small devices. It's quite simple.

/* Large screens */ .navigation ( display: flex; flex-flow: row wrap; /* This will align the elements to the end of the line on the main axis */ justify-content: flex-end; ) /* Medium screens */ @ media all and (max-width: 800px) ( .navigation ( /* On medium-sized screens, we center elements by evenly distributing white space around the elements */ justify-content: space-around; ) ) /* Small screens */ @media all and (max-width: 500px) ( .navigation ( /* On small screens we no longer use row direction, but column */ flex-direction: column; ) )

Large screens


Medium screens


Small screens



Let's try something even better by playing with the flexibility of flex elements! How about a 3-column, full-height page layout with a header and footer. And does not depend on the initial order of the elements.

Wrapper ( display: flex; flex-flow: row wrap; ) /* We say that all elements have a width of 100%, via flex-base */ .wrapper > * ( flex: 1 100%; ) /* We use the original order for the first mobile option * 1. header * 2. article * 3. aside 1 * 4. aside 2 * 5. footer */ /* Middle screens */ @media all and (min-width: 600px) ( /* We tell both sidebars to be on the same line */ .aside ( flex: 1 auto; ) ) /* Large screens */ @media all and (min-width: 800px) ( /* We invert the order of the first sidebar and the main one and say to the main element so that it takes up twice the width of the other two sidebars */ .main ( flex: 2 0px; ) .aside-1 ( order: 1; ) .main ( order: 2; ) .aside-2 ( order : 3; ) .footer ( order: 4; ) )

@mixin flexbox() ( display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; ) @mixin flex($values) ( -webkit- box-flex: $values; -moz-box-flex: $values; -webkit-flex: $values; ) @mixin order($val) ( -webkit- box-ordinal-group: $val; -moz-box-ordinal-group: $val; -ms-flex-order: $val; -webkit-order: $val; flexbox(); .item ( @include flex(1 200px); @include order(2); )

Errors

Flexbox is of course not without its bugs. The best collection of these I've seen is Flexbugs by Philip Walton and Greg Whitworth. This is an open repository source code to keep track of all of them, so I think it's best to just link to it.

Browser support

Broken down by flexbox “version”:
  • (new) means recent syntax from the specification (for example display: flex;)
  • (tweener) means strange unofficial syntax since 2011 (eg display: flexbox;)
  • (old) means old syntax since 2009 (eg display: box;)

Blackberry Browser 10+ supports the new syntax.

For getting additional information on how to mix syntaxes to get better browser support, please refer to

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. In the beginning, web pages were like single threaded text documents, a little later, dividing the page into blocks was done with tables, then it became fashionable to typeset with floats, and after the official death of ie6, techniques with inline-block 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 CSS property flex-wrap is responsible for multi-line content inside a flex container.

Available values - down up.:

  • 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 – flex elements are lined up in one line; if they do not fit into the container, they go beyond its boundaries (by default);, 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 will be ignored.:

  • 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;)

In short, layout with Flexbox gives us simple solutions once difficult tasks. 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, anyone HTML element just 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, which 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.

  • , 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.- 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 (→)
  • - from right to left;- direction of elements from top to bottom (↓)
  • – from left to right (default);- direction of elements from right to left (←)
  • - top down;- 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.
  • – flex elements are lined up in one line; if they do not fit into the container, they go beyond its boundaries (by default);- 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.
  • – flex elements are lined up in several lines if they do not fit into one;- 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)
  • – flex elements are pressed to the beginning of the main axis (by default);- the elements will go from the beginning (there may be some space left at the end).
  • – flex elements are pressed against the end of the main axis;- elements are aligned at the end (the space will remain at the beginning)
  • – flex elements are aligned to the center of the main axis;- in the center (space will remain on the left and right)
  • – 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;- the outermost elements are pressed against the edges (the space between the elements is distributed evenly)
  • space-evenly
- 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.

align-content:

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
  • Determines the alignment of elements along the major axis. Possible values:- rows are grouped at the top of the container (there may be some space left at the end).
  • – flex elements are pressed to the beginning of the main axis (by default);- rows are grouped at the bottom of the container (space will remain at the beginning)
  • – flex elements are pressed against the end of the main axis;- rows are grouped in the center of the container (space will remain at the edges)
  • – flex elements are aligned to the center of the main axis;- the outer rows are pressed against the edges (the space between the rows is distributed evenly)
  • – 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;- 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 of the outer elements to 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
  • Determines the alignment of elements along the major axis. Possible values:- elements are pressed to the beginning of the row
  • – flex elements are pressed to the beginning of the main axis (by default);- elements are pressed to the end of the row
  • – flex elements are pressed against the end of the main axis;- elements are aligned to the center of the row
  • – flex elements are pressed against the end of the transverse axis;- 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

  • 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”;- the element is stretched to fill the line completely
  • Determines the alignment of elements along the major axis. Possible values:- the element is pressed to the beginning of the line
  • – flex elements are pressed to the beginning of the main axis (by default);- the element is pressed to the end of the line
  • – flex elements are pressed against the end of the main axis;- the element is aligned to the center of the line
  • – flex elements are pressed against the end of the transverse axis;- 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 css. Therefore, see examples in latest versions Chrome or Firefox.

#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 using 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. Every indoor unit is also a flex construction, 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; -ms-flex-direction:column; -ms-flex-wrap:wrap; -flex-flow:column wrap; -webkit-box-pack:justify; -ms-flex-pack:justify; 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; -ms-flex:1 2 100px; :center; align-self:center; -webkit-box-ordinal-group:3; -ms-flex-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.

flex-direction: column;

You"ll see that this puts the items back in a column layout, much like they were before we added any CSS. Before you move on, delete this declaration from your example.

Note: You can also lay out flex items in a reverse direction using the row-reverse and column-reverse values. Experiment with these values ​​too!

Wrapping

One issue that arises when you have a fixed amount of width or height in your layout is that eventually your flexbox children will overflow their container, breaking the layout. Have a look at our flexbox-wrap0.html example, and try viewing it live (take a local copy of this file now if you want to follow along with this example):

Here we see that the children are indeed breaking out of their container. One way in which you can fix this is to add the following declaration to your element represents a standalone section - which doesn"t have a more specific semantic element to represent it contained within an html document.>

rule:

Flex-wrap: wrap;

flex: 200px;

Try this now; you"ll see that the layout looks much better with this included:

We now have multiple rows - as many flexbox children are fitted onto each row as makes sense, and any overflow is moved down to the next line. The flex: 200px declaration set on the articles means that each will be at least 200px wide; we"ll discuss this property in more detail later on. You might also notice that the last few children on the last row are each made wider so that the entire row is still filled.

But there"s more we can do here. First of all, try changing your flex-direction property value to row-reverse - now you"ll see that you still have your multiple row layout, but it starts from the opposite corner of the browser window and flows in reverse.

flex-flow shorthand

At this point it is worth noting that a shorthand exists for flex-direction and flex-wrap - flex-flow. So for example, you can replace

Flex-direction: row; flex-wrap: wrap;

Flex-flow: row wrap;

Flexible sizing of flex items

Let's now return to our first example, and look at how we can control what proportion of space flex items take up. Fire up your local copy of flexbox0.html , or take a copy of flexbox1.html as a new starting point ( see it live).

First, add the following rule to the bottom of your CSS:

Article (flex: 1; ) element a value of 1, which means they will all take up an equal amount of the spare space left after things like padding and margin have been set. It is a proportion, meaning that giving each flex item a value of 400000 would have exactly the same effect.!}

Now add the following rule below the previous one:

Article:nth-of-type(3) ( flex: 2; )

Section - article article article - div - button div button div button button button

Let's look at the code we've used for the layout.

Summary

That concludes our tour of the basics of flexbox. We hope you had fun, and will have a good play around with it as you travel forward with your learning. Next we"ll have a look at another important aspect of CSS layouts - CSS Grids.

Start