Go to homepage

Projects /

May 28, 2020

Flex gap using negative margins

By CodyHouse
404 HTML, CSS, JS components. Download →

How to add a gap between flex items using negative margins.

While we wait for more browsers to support flex-gap, here's a workaround you can use right now to create a gap between your flex items. It relies on positive margins applied to the flex items and negative margins applied to the flex (parent) element.

.stack {
  --gap: 0.5rem; /* 👈 gap control */
  display: flex;
  flex-wrap: wrap;
  margin-bottom: calc(-1 * var(--gap));
  margin-left: calc(-1 * var(--gap));

.stack > * {
  margin-bottom: var(--gap);
  margin-left: var(--gap);

This method has the main advantage of applying the gap either if the items are stacked horizontally (same row), or vertically.

Here's an example:

Soon enough we'll be able to use the gap property and this trick will no longer be needed.

Using the gap property:

.stack {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;

Project duplicated

Project created

Globals imported

There was an error while trying to export your project. Please try again or contact us.