Flexbox-level collapse of children

I have the following layout through flexbox with flexible packaging and stretchable elements using flex-grow:

flexbox

Each element has a margin on all sides. It is necessary to separate the elements from each other, but the side effect is the whole block with the fields that I would like to collapse. This can be done using rules such as nth-child(-n+3) { margin-top: 0; } nth-child(-n+3) { margin-top: 0; } , but since the size of the container can vary, there can be any number of elements in a row and any number of rows. Therefore, I am wondering if the flex-box has any way to collapse external fields in this configuration, while preserving the fields between the elements.

Jsbin

HTML is just 6 elements inside a container.

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 
+7
css margin flexbox
source share
1 answer

This is a bit hacky, but you can add a negative margin to the flex container to undo the margins of the elements around the edges and then move its background style to the parent wrapping 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 
+4
source share

All Articles