Interactive online courses HTML Academy
2026-03-09 14:09 Diff

We didn‘t mention the margin property in the previous assignment, because it comes with a number of surprises:

  • Margins do not collapse either horizontally or vertically.

  • Margins do not overflow either the flex container or flex items.

  • The auto value received the Forbes magazine award in the category “The Most Influential Value for a CSS Property Inside a Flex Container”.

It all has to do with the mechanism that is used to allocate free space. If there is free space inside a flex container, then it is redistributed as follows:

  1. There are items with margins that have been assigned the value auto;

  2. All of the free space in the corresponding directions is allocated to these margins (in other words, a certain margin size is set in pixels).

  3. If there are several items with automatic margins set in one direction, then the space between them is redistributed equally.

  4. It is only once these items are spaced properly that the alignment mechanisms are allowed to act on them.

Therefore, margin: auto; affects the positioning of flex items on both axes, and is also supersedes alignment mechanisms, because alignment occurs when there is free space. But if all of the free space overflows into the automatic margin, then there is nothing to align.

These features can be used to good effect. For example, you can control the arrangement of the items along the main axis using automatic margins. Let’s experiment.