Margin collapsing in flexbox
Margin collapsing is a feature of a block formatting context.
There is no margin collapsing in a flex formatting context.
3. Flex Containers: the
flex
andinline-flex
display
valuesA 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. For example, floats do not intrude into the flex container, and the flex container’s margins do not collapse with the margins of its contents.
though margin collapse is not possible with flexbox, you can use gap
to achieve the same result:
.parent {
display: flex;
flex-wrap: wrap;
flex-direction: row;
column-gap: 5px;
row-gap: 15px;
max-width: 70px;
outline: 1px solid #440;
}
.parent > div {
background: #8ff;
width: 20px;
height: 20px;
}
<div class="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
https://coryrylan.com/blog/css-gap-space-with-flexbox
NOTE: This is not a way to make margins behave in a flex box layout the same way as they do in a block layout; however, this may help resolve the margin problem in some cases.
Instead of relying on collapsing margins, you can use pseudo selectors to get the effect you want:
main{
display: flex;
flex-direction: column;
margin-bottom: 20px;
}
article{
margin-bottom: 20px;
background: #eee;
}
article:last-child{
margin-bottom: 0;
}
footer{
background: #eef;
}
<main>
<article>
This is article number 1
</article>
<article>
This is article number 2
</article>
<article>
This is article number 3
</article>
</main>
<footer>
This is the footer of the page
</footer>