Typically, in CSS, when a parent and its last child have a margin, the margins collapse to create a single margin. E.g.
article {
margin-bottom: 20px
}
main {
background: pink;
margin-bottom: 20px;
}
footer {
background: skyblue;
}
<div id="container">
<main>
<article>
Item 1
</article>
<article>
Item 2
</article>
</main>
<footer>Footer</footer>
</div>
As you can see, even though a margin of 20px
is specified on both the article
and the main
tags, you only get a 20px
margin between the last article and footer.
When using flexbox, however, we get a 40px
margin between the last article and footer — a full 20p
x margin from the article to main, and another 20px
from main to footer.
#container {
display: flex;
flex-direction: column;
}
article {
margin-bottom: 20px
}
main {
background: pink;
margin-bottom: 20px;
}
footer {
background: skyblue;
}
<div id="container">
<main>
<article>
Item 1
</article>
<article>
Item 2
</article>
</main>
<footer>Footer</footer>
</div>
Is there a way to make flexbox margins behave the same way as the non-flexbox ones?