0

I need to center a flex container (green, dashed outline). The flex parent should even be centered, when the flex items are wrapping and leaving whitespace like on the right side of the screenshot.

The issue is that display: flex takes all available width, while we would need it to take minimum-width with the most flex-items in the first row.

You can find a jsfiddle here: https://jsfiddle.net/3qeodz6a/7/

body {
  margin-left: 32px;
  margin-right: 32px;
  display: flex;
  justify-content: center;
}

.container {
  outline: 1px solid red;
  padding: 10px;
  
  // We want a maximum of 4 columns
  max-width: calc(120px * 4 + 32px * 3)
}

.headline {
  outline: 1px solid blue;
}

.modules {
  outline: 1px dashed green;
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
}

.m {
  width: 120px;
  height: 40px;

  outline: 1px solid aqua;
}
<div class="container">
  <div class="headline">
    Headline
  </div>
  <div class="modules">
    <div class="m">
      Module 1
    </div>
    <div class="m">
      Module 2
    </div>
    <div class="m">
      Module 3
    </div>
    <div class="m">
      Module 4
    </div>
    <div class="m">
      Module 5
    </div>
    <div class="m">
      Module 6
    </div>
  </div>
</div>

JS Fiddle as Screenshot

JoCa
  • 1,045
  • 9
  • 14
  • Basically this is not possible with flexbox. That's not the way the box model works - https://stackoverflow.com/questions/37406353/make-container-shrink-to-fit-child-elements-as-they-wrap – Paulie_D Jun 25 '21 at 16:07
  • @Paulie_D It might be possible with css grids. Can you tell if it is? – JoCa Jun 25 '21 at 16:13
  • Not without specifying the number of columns I suspect. You'd have to try. – Paulie_D Jun 25 '21 at 16:14

1 Answers1

1

You could put justify-content:center on the modules class so that when it becomes 3 items on a row it centers leaving gaps on the sides but you won't be able to make the modules container itself scale down to fit the width of the columns.

.modules {
  outline: 1px dashed green;
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
  justify-content: center;
}

The other thing you could do is make the width of the columns flexible and then you can use css grid to specify how many columns you want a certain breakpoints using media queries and then the columns would fill the available space whether there are 2, 3 or 4 items in a row.

.modules {
  outline: 1px dashed green;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 32px;
}
@media screen and ( max-width: calc(120px * 4 + 32px * 3) ) {
 .modules {
   grid-template-columns: repeat(3, 1fr);
  }
}
David
  • 136
  • 5