Search code examples
htmlcssflexbox

How can I set a minimum amount of space between flexbox items?


Given this CSS:

div.container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  border: 1px solid blue;
}
div.container div {
  width: 200px;
  border: 1px solid gray;
  display: inline-block;
  text-align: center;
}

This layout has the first item in each row aligned to the left, and the last item aligned to the right, as required.

As the browser window is made narrower, the distributed div elements will move closer together until they touch, at which point they are re-arranged over an additional row. Again, the first div on each row is aligned left, and the last aligned right with space between.

Is there any way of setting a minimum spacing so that the inner div elements always have a gap between them.

padding and margin will probably not work, as the alignment

<-- 1st left in row and last right in row --> will not hold.


Solution

  • You can add another div with flex style for holding the needed gap between inner divs. and for the minimum width for that gap use this property (as mentioned in W3Schools.com):

    flex: flex-grow flex-shrink flex-basis|auto|initial|inherit;

    which flex-shrink is :

    flex-shrink: A number specifying how much the item will shrink relative to the rest of the flexible items

    so, for example you set this css code for the gap div :

    flex: 1 0 10px;
    

    that tells gap div will have 10px width, and will grow relative to the rest of the flexible items, but WON'T SHRINK. so the minimum width will be 10px at the narrowest width of the screen.