Gaps
The flex container can insert gaps between flex items and between flex lines.
Having the flex container insert gaps between flex items or flex lines is the easiest and safest way to ensure spacing between items.
“Between” is the key word here. This is super useful if your flex container is already setting some padding, and you want to make sure there’s space between, but not around flex items.
Gaps are non-negotiable
They always exist between two flex items and will have the exact size specified.
Because there must be a gap between any two flex items on a flex line, this affects whether flex items can fit on a flex line.
And it decreases the amount of space available to flex items for growing.
The gap
shorthand is the fastest way to insert gaps
Is a shorthand that sets both column-gap
and row-gap
. It’s a shortcut.
For example, when you set gap: 8px
on an element, that element will have column-gap: 8px
and row-gap: 8px
.
This means an 8-pixel gap will be inserted between any two flex items on the same line, or any two flex lines if you have a flex container that allows its flex items to wrap and they did wrap into multiple flex lines.
Inserting different gaps between flex items and flex lines.
Instead of using the gap
shorthand, you need to use the column-gap
and row-gap
longhands.
Which gap these properties refer to depends on the writing direction of the flex container.
In a flex container with : row
, flex items are laid out in the direction of words in a row of text. In English, that’s left to right.
Columns of text are also laid out in that direction in English. They stack from left to right.
So if you want to insert a gap between flex items when : row
, you have to set column-gap
. That’s because you’re flex items are kind of like columns in this sense.
Yes, it’s confusing. I recommend sticking to the gap
property, and only resorting to the longhand properties when you have a multi-line flex container and you need to have different gaps between flex items and flex lines.
Gaps are added to the space distributed with alignment properties.
Gaps are always inserted between flex items and flex lines, and they add up to space distributed with alignment properties.
For example, you could set : space-evenly
, which will evenly divide up the remaining space on a flex line, and place each part around and between flex items. If you’re also inserting a gap of 8px
, the space between the flex items will be greater than the space around the flex items by the edge of the flex container.