10

When I use flexbox, if I want a margin to add spacing to each element I would usually do this:

.flexbox-item {
  flex: 1 0 auto;
  margin-right:10px;
}
.flexbox-item:last-of-type {
  margin-right: 0px;
}

This works if I don't use flex-wrap because they last item will always be the actual last item on the row.

When I use flex-wrap however, the last item of the row changes depending on the window width (and more rows are added automatically), meaning I'm removing the right margin from the 1st item in a row sometimes.

Anyone know of a solution to this issue?

EDIT: I don't believe this is a duplicate

This is about keeping rows horizontally equal, not vertically.

Anyway, my solution is using negative margins which can found on that thread by digging through it but it's not the most popular solution. Here's my solution:

Seems that the answer to this issue is to add a negative margin to the parent flexbox container.

.flexbox-container {
  margin-right:-10px;
}
.flexbox-item {
  flex: 1 0 auto;
  margin-right:10px;
}

Then when your flexbox items change to 100%, just remove the right margin from the items:

@media (max-width: 767px) {
    .flexbox-item {
      margin-right:0px;
    }
    .flexbox-container {
      margin-right: 0px;
    }
}

If there is a better solution I'm all ears.

4ndy
  • 446
  • 7
  • 26
  • 4
    https://stackoverflow.com/a/46775239/3597276 – Michael Benjamin Nov 29 '17 at 17:36
  • 2
    Thanks for the response. Can't use css grid but did learn from that thread about the negative margin trick on the parent element. Seems hacky but it is effective. – 4ndy Nov 29 '17 at 17:59
  • You might also be able to use `space-between` combined with a top margin (less hackier than negative margins) ... https://stackoverflow.com/questions/47537544/equal-distance-between-divs-using-angular-5-and-flex-layout/47539601#47539601 – Asons Nov 29 '17 at 18:01

1 Answers1

0

I'm not entirely sure about your use-case. But why not use justify-content: space-between instead of margin. Then you don't need to remove margin for the last element in the row. https://jsfiddle.net/n2vqwg79/

Shriharsha KL
  • 317
  • 1
  • 2
  • 11
  • 1
    Sure, but what happens when there's no space-between? The items are sandwiched together. It is at that point that I really need a right-margin. – 4ndy Nov 29 '17 at 17:48
  • I'm not sure if that is even possible. – Shriharsha KL Nov 29 '17 at 17:54
  • 5
    If we have multiple rows and the last row has fewer items than other rows, the alignment of the last row is going to look weird. – hudidit May 05 '19 at 14:04
  • 1
    If you have no backward compatibility issues, just set the `gap` property on the flex container, this will guarantee a minimal gap between columns. Check for availability at https://caniuse.com/?search=gap – Will59 Oct 27 '21 at 14:21