In this example, a flex container contains six flex items of two different widths (200px
and 300px
), creating flex items that are not laid out as a grid. The column-gap
property is used to add horizontal space between the adjacent flex items.
HTML
<div class="flexbox">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
CSS
To create a flex container, we set its display
property value to flex
. We then use the flex-flow
shorthand property to set the flex-direction
to row (the default) and flex-wrap
to wrap
, allowing the flex items to flow onto new lines if needed. By default, flex items stretch to be as tall as their container. By setting a height
, even the empty flex items will be 100px
tall.
To better demonstrate the column-gap
property, the flex items in this example have two different width values. The width of the flex items is set within the <div>
flex items. We use the flex-basis
component of the flex
shorthand property to make all the flex items 200px
wide. We then target every third flex item by using the :nth-of-type(3n)
selector, widening them to 300px
.
The column-gap
value is set as 20px
on the flex container to create a 20px
gap between the adjacent flex items in each row.
.flexbox {
display: flex;
flex-flow: row wrap;
height: 100px;
column-gap: 20px;
}
.flexbox > div {
border: 1px solid green;
background-color: lime;
flex: 200px;
}
div:nth-of-type(3n) {
flex: 300px;
}
Result
Note: While there is horizontal space between adjacent flex items in each flex row, there is no space between the rows. To set vertical space between flex rows, you can specify a non-zero value for the row-gap
property. The gap
shorthand property is also available to set both the row-gap
and column-gap
in one declaration, in that order.