Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 Flexbox spacing between items

Tags:

Being somewhat new to Flexbox (although experienced in CSS), it seems to me that one thing conveniently "glossed over" by most tutorials I've read is the spacing between flex items.

For example, one of the most cited tutorials is this one at CSS Tricks.

It's very good and has been helpful, diagrams like this have thrown me off:

enter image description here

Notice the spaces between the flex items. Although not mentioned anywhere, nor in the sample code, it would seem the only way to get the spaces is with css margins.

Correct, or am I missing something important here?

Because what i need to create is this, a lot like the "center" demo above: enter image description here

However, when I try it myself, I of course get this: enter image description here

if I use space-around, I get this instead. Huge space. enter image description here

Therefore it seems I need to add margin-right to the first 2 boxes to get 3 centered boxes with a small gap between them.

Is this simply a bad use case for Flexbox? Because I see little advantage creating my 3 boxes with Flexbox over using simple margins and centering.

Am I missing something obvious here?

like image 584
Steve Avatar asked Jun 13 '15 03:06

Steve


People also ask

How do I give space between items in flexbox?

The flexbox layout even works when the size of the items is unknown or dynamic. To set space between the flexbox you can use the flexbox property justify-content you can also visit all the property in that link. We can use the justify-content property of a flex container to set space between the flexbox.

How do I reduce the gap between my Flex items?

Setting a flex-basis with percentage also will do the trick. Then the min space between will be also in percentage. For instance, with 3 elements, flex: 0 0 30% will allow a fixed 10% space reparted between elements.

Can I use gap with Flex?

As you see, the gap works perfectly for both CSS grid and flex - on the browsers that support them.

What is the space between to items?

space-between : items are evenly distributed in the line; first item is on the start line, last item on the end line. space-around : items are evenly distributed in the line with equal space around them.


1 Answers

Nope - you're not missing anything. Flexbox is terrific for ordering elements and defining the general alignment of those elements along either the main or cross axes, but doesn't speak directly to individual item spacing. If you take a look at this Codepen used in the Flexbox article, you'll notice they use:

margin-top: 10px 

to define element spacing. Hope this helps!

like image 166
Ryan Miller Avatar answered Sep 22 '22 14:09

Ryan Miller