In traditional CSS, when a parent element and its last child both have margins, the margins collapse into a single margin. However, when using Flexbox, this collapsing behavior changes.
In Flexbox, elements are aligned within a flex container using the display: flex property. This creates a flex formatting context, which differs from a block formatting context in terms of margin collapsing.
In a block formatting context, margins collapse as follows:
article { margin-bottom: 20px; } main { margin-bottom: 20px; } footer { margin-top: 20px; } <!-- Outputs a 20px margin between the last article and footer -->
However, in a flex formatting context, margins do not collapse:
#container { display: flex; flex-direction: column; } article { margin-bottom: 20px; } main { margin-bottom: 20px; } footer { margin-top: 20px; } <!-- Outputs a 40px margin between the last article and footer -->
This difference in behavior is due to Flexbox's separate formatting rules. In a flex context, margins are applied individually to each element within the container, resulting in non-collapsed margins.
The above is the detailed content of How Does Margin Collapsing Differ Between Traditional CSS and Flexbox?. For more information, please follow other related articles on the PHP Chinese website!