Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapsing margin on Flexbox children

I have the following arrangement via flexbox with flex-wrap and elements able to stretch using flex-grow:

flexbox

Each item has a margin on all sides. This is to separate the items from each other, but the side effect is the whole block has margins which I'd like to collapse. It could be done with rules like nth-child(-n+3) { margin-top: 0; } but because the container size could vary, there could be any number of items per row and any number of rows. So I'm wondering if flex-box has any way to collapse the outer margins in a setup like this, while retaining the margins between items.

JSBin

The HTML is simply 6 items inside a container.

The CSS (Sass) is as follows:

.container
  display: flex
  flex-wrap: wrap
  background: #eef
  align-items: stretch

.item
  flex-grow: 1  
  margin: 1em
  border: 1px solid black
  padding: 1em
  min-width: 6em
like image 402
mahemoff Avatar asked Nov 21 '14 10:11

mahemoff


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.

How do you prevent margin collapse?

How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.

Which scenario margin will collapse?

Margin collapsing occurs in three basic cases: Adjacent siblings. The margins of adjacent siblings are collapsed (except when the latter sibling needs to be cleared past floats). No content separating parent and descendants.

Why is margin not collapsing?

Margins of elements do not collapse when the value of the overflow property of the elements is set to anything other than visible. Its value must be visible so that margin can collapse.


1 Answers

It's a bit of a hack, but you can add a negative margin on the flex container to cancel out the items' margins along the edges, and then move its "background" styling to a parent wrapper-element.

Updated JSBin

Updated CSS (SASS):

.wrapper
  background: #eef
  border: 1px solid darkgray

.container
  display: flex
  flex-wrap: wrap
  margin: -1em

.item
  flex-grow: 1  
  margin: 1em
  border: 1px solid black
  padding: 1em
  min-width: 6em
like image 130
dholbert Avatar answered Oct 07 '22 21:10

dholbert