Codectionary / Developer documentation / CSS

Spacing Flex Items with gap

gap supplies spacing between flex items and flex lines without adding margins around the container’s outside edges.

What it is and why to use it

gap supplies spacing between flex items and flex lines without adding margins around the container’s outside edges. It is useful for wrapping tags, navigation items and button groups. Its two-value form describes row and column gaps, whose practical effect depends on flex direction.

Common mistakes and limitations

gap does not replace container padding. Percentage gaps can have non-obvious sizing behaviour, so fixed or relative lengths are often clearer here. Older browser versions may lack flex-gap support even if they support grid gap; check the relevant feature.

Try the example

The example pairs editable CSS with its own HTML preview. Run it, then change one declaration at a time and compare the result. Locally, put the CSS in a style element in the document head or in an external stylesheet linked from the HTML. Feature support varies by browser and version; use the linked reference and a useful fallback where needed.

HTML used by this example

<div class="tags"><span class="tag">HTML</span><span class="tag">TypeScript</span><span class="tag">CSS</span><span class="tag">Accessibility</span></div>

Syntax

display: flex; gap: .5rem 1rem;

Examples

Spacing Flex Items with gap

Run the CSS against the supplied HTML, then experiment with the values.

.tags { display: flex; flex-wrap: wrap; gap: .5rem 1rem; max-width: 18rem; }
.tag { padding: .5rem; background: #dbeafe; color: #172b4d; border-radius: .25rem; }
  1. Items wrap when the row has insufficient space.
  2. The row-direction layout uses a 1rem gap between items and a .5rem gap between lines.
  3. No leading or trailing outer gap is created. This makes consistent tag spacing easier than assigning margins to every child.
HTML used by this example
<div class="demo"><div class="tags"><span class="tag">HTML</span><span class="tag">TypeScript</span><span class="tag">CSS</span><span class="tag">Accessibility</span></div></div>

Best practices

  • gap does not replace container padding. Percentage gaps can have non-obvious sizing behaviour, so fixed or relative lengths are often clearer here. Older browser versions may lack flex-gap support even if they support grid gap; check the relevant feature.
  • Inspect the relevant browser reference and test the browsers used by your audience.

Runtime & versions

Web browsers. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

CSS specifications (modules)

Specifications & further reading