Search code examples
cssmarginflexbox

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

Solution

  • 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