Gap and Layout Spacing

Learn about dynamic spacing techniques in flexbox and grid layouts using the gap property, demonstrated with the clamp() function and vmax unit.

Difference between gap and margin

When using flexbox or grid layout, we have access to the gap property. Although it exists between elements, it differs from margin in a few key ways:

  • Its default value is 0, with no browser defaults to override.

  • It can be set independently for the row or column axis.

  • It’s only applied internally to a flex or grid layout, not outside a flex or grid container.

  • It’s only reserved when there are multiple elements and only on the necessary axis.

  • It can’t be overridden for a particular item; it remains uniform between items on a given axis.

Note: The gap shorthand accepts either a single value—which sets both row and column space—or two values, where the first is for rows and the second for columns.

These differences from margin allow us to offload some spacing decisions to the browser. We have to manage which direction margin applies, and possibly use media queries to adjust it, such as when there’s a change in layout orientation. With gap, we only need to provide one or two values (two if we want the row gap and column gap to be different), and the browser will only include that space in the layout when necessary.

For components that closely set text content as flex or grid items—such as navigation menus—we may want to use more static values or low-range clamp() scales such as those used by Utopia.

However, when defining larger page layouts with either flexbox or grid, we might consider setting gap with a method that’s dynamic in relation to the viewport.

Creating a responsive layout using clamp() with vmax

Let’s revisit clamp(), but this time using a responsive value of vmax , which is the viewport maximum unit. If the viewport width is greater than the height, then 1vmax will equal 1% of the width. If the viewport height is greater than the width, then 1vmax will equal 1% of the height.

Now we’ll set up similar utility classes as we did for padding, except that we’ll define these specifically as layout gap values to indicate they should be used for structural components like layout grids.

As a reminder, the use of clamp() allows us to provide boundaries to prevent space becoming either too small or too large. When using vmax , we’re basically asking the browser to create more space in relation to the more roomy axis, which enables adapting to different orientations of devices as well:

Get hands-on with 1200+ tech skills courses.