Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margin collapsing in flexbox

Tags:

css

flexbox

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 20px 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?

like image 408
Coffee Bite Avatar asked May 10 '17 02:05

Coffee Bite


People also ask

Does Flexbox collapse margins?

There is no margin collapsing in a flex formatting context. 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.

Why are my margins collapsing?

Margin collapse occurs when vertically adjacent margins of block-level elements collide to share a general margin space. The size of this shared space is dictated by the larger number margin.

How do I stop my margins collapsing?

To prevent margin collapsing between siblings, add display: inline-block; to one of the siblings (one is enough though you can add it to both).


1 Answers

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 and inline-flex display values

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. 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.

like image 122
Michael Benjamin Avatar answered Oct 21 '22 00:10

Michael Benjamin