Margin Collapsing in Flexbox
In CSS, margins on adjacent elements typically collapse to create a single margin. However, in flexbox containers, this behavior differs.
The Issue: Non-Flexbox vs. Flexbox Margins
When using non-flexbox layout, margins on a parent element and its last child collapse:
article { margin-bottom: 20px; } main { margin-bottom: 20px; }
However, in a flexbox container:
#container { display: flex; flex-direction: column; } article { margin-bottom: 20px; } main { margin-bottom: 20px; }
The margins no longer collapse, resulting in a larger gap between the last article and footer.
Understanding the Difference
Margin collapsing occurs in block formatting contexts. However, flexbox containers create a different type of context called a flex formatting context.
According to the CSS Box Model specification:
"A flex container establishes a new flex formatting context for its contents. This is the same as establishing a block formatting context, except that flex layout is used instead of block layout."
In a flex formatting context, margins do not collapse because the contents are treated differently rispetto a normal block layout. Floats do not intrude into the flex container, and the container's margins remain separate from the margins of its child elements.
The above is the detailed content of How Do Margins Behave Differently in Flexbox Compared to Standard CSS Layout?. For more information, please follow other related articles on the PHP Chinese website!