• Post category:CSS

How to Add Space Between Flex Items in CSS Using Gap ?

Flex Gap CSS

In this article, we will see How to make a flex gap in CSS.


<div class="stack">
<button class="btn btn-primary">Button1</button>
<button class="btn btn-primary">Button2</button>
<button class="btn btn-primary">Button3</button>


display: flex;
flex-wrap: wrap;
--gap: 0.5rem;}

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


flex gap css

  1. Here, we have created a <div> within that we have three buttons. We have given a classname “stack” for <div> tag.
  2. In CSS, we selected the <div> tag using the classname selector “stack”. Then we set the “display” property to “flex”, and “flex-wrap” to ” wrap”, which means if the buttons don’t fit in the viewport instead of having horizontal scrolling they will break into multiple lines.
  3. To make a flex gap, we need to set the CSS “gap” property to your desired gap size. But here, we cannot use the gap property because we have a set flex display. If we use a grid display we can use the gap property.
  4. ¬†Instead of using the gap property, we should switch to a CSS custom property that we define as “–gap”¬†as in the above code.
  5. To insert a gap between each button, we have to create a function for a separate button in the div tag, for that, we have given the notation like “stack > *”.
  6. Inside the function, we have to give “margin-left” to “var(–gap)”.¬†See the above output, the spacing for each button is perfectly created.
READ ALSO  How to Disable Text Selection in CSS | Explained

Leave a Reply