1

Im using flexboxgrid library to create easy responsive layout, I have a parent div styled like so

display: flex;
flex-wrap: wrap;
gap: 2rem;

children have flexboxgrid styling

col-xs-12 col-md-6 col-lg-4

and it works otherwise well, except when I put that 'gap: 2rem' on parent, then div's start overflowing and push last item to another row.

To illustrate problem:

Gap problem

How can I fix it ?

EDIT: Link to CodePen, with gap there is 2 rows, without gap 1 row. How to keep gap, stay on 1 row ?

https://codepen.io/ShinigamiZ/pen/YzezgwE

Jeekim
  • 543
  • 5
  • 15

2 Answers2

1

If you want to spread them out over the whole width, don't set a flex-basis for the elements. Rather set flex-grow: 1. This means, that the elements will grow to be as big as possible.

If you want to wrap them to a new line, you need to alter your calculation for flex-basis to also incorporate the gap.

.parent {
  display: flex;
  flex-wrap: wrap;
  gap: 2rem;
  background-color: yellow;
}

.sib {
  background-color: gray;
  flex-grow: 1;
}
<div class='parent'>
  <div class='sib'>
    123
  </div>
  <div class='sib'>
    123
  </div>
  <div class='sib'>
    123
  </div>
</div>
cloned
  • 6,346
  • 4
  • 26
  • 38
0

Column classes (col-xs-12 col-md-6 col-lg-4) means it's percentage width and that's where the issue is because the gap is not included in percentage calculation.

My take on this is to allow the columns shrink and grow but only by the amount of gap you define. With your example that would be something like:

.col-md-6 {
  flex: 1 0 calc(50% - 2rem);
  max-width: 50%;
}

The only issue is a slight inconsistency with columns width if there's a empty space left or if it's the only column and not fullwidth as the elements have their own original percentage width and not one reduced by gap.

https://codepen.io/Erehr/pen/jOxYadW

Erehr
  • 11
  • 2