Controlling the amount of space in justify-content: space-between

The approach with using margins is not a universal solution if you want space-between, because it would set a margin on all the flex-elements, also on the first and last elements on a line or column. Using :first-child / :last-child/ :nth-child() selector doesn't help when flex-wrap: wrap is set, because you can never tell which elements will be first and last on a wrapped line or column.

A selector like :wrapped would be helpful, but sadly it doesn't exist.

So my conclusion is that when you really want to unleash the flexibility and responsiveness of the flexbox, you can't control the margins… Missed opportunity of the spec I'd say.


The justify-content property uses the available space on the line to position flex items.

With justify-content: space-between, all available space is placed between the first and last items, pushing both items to opposite edges of the container.

You wrote:

I was wondering how to justify how much space is allowed in justify-content: space-between for flexbox.

With space-between in row-direction, you would have to control the width of the flex container. So if you want there to be less space between flex items, then you would need to shorten the width of the container.

Or you could use justify-content: space-around.

However, these solutions are suboptimal.

The right way to go about this would be to use margins.

You wrote:

Currently, my items are spaced but they have way too much space between them I want just a little space between them so they can settle somewhere in the middle in a row.

Use justify-content: center then use margins to space them apart.


I find myself adding right margin to all the boxes (in this case three)

.three {
    margin-right: 2%
}

and then getting rid of it so the last box aligns right

.three:nth-child(3) {
    margin-right: 0%;
}

but every time I do this I think "there has to be a better way, something baked into flex-box...this works but it seems like a workaround?


My solution was :

  • put dummy empty divs in between with a max-height specified
  • change space-between to flex-start
  • set the content blocks to nogrow
  • set the dummy divs to grow

Then the spaces grow up to a max specified.

Tags:

Html

Css

Flexbox