'How to make the items in the flexbox align in the center and to the left [duplicate]

Proposed layout

I've made a 3 column flexbox and I need all flexbox items to be in the center and the items that are in rows that are not full to be center and aligned to the left. What would you guys recommend?

I currently have the below but the bottom row is aligning in the center.

.flexbox {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 50px;
}


Solution 1:[1]

Using justify-content: center; will always put the odd flex item in the center with flex-wrap when resizing. I would suggest using a different way to center the flex container. In this case, I used width: fit-content with margin: auto; to center. You could also use a max-width on the flex parent. I used space-between to space the flex items as using a static gap is not as responsive.

See the notes below:

.flexbox {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: fit-content; /* allows margin auto to center */
  margin: auto;
}

.flex-item {
  width: calc(100%/3.1); /* .1 for spacing paired with space-between for smaller screens */
}

img {
  max-width: 100%; /* responsive images */
}
<div class="flexbox">
  <div class="flex-item">
    <img src="https://dummyimage.com/300/000/fff">
    <h6> Hello World </h6>
  </div>
  <div class="flex-item">
    <img src="https://dummyimage.com/300/000/fff">
    <h6> Hello World </h6>
  </div>
  <div class="flex-item">
    <img src="https://dummyimage.com/300/000/fff">
    <h6> Hello World </h6>
  </div>
  <div class="flex-item">
    <img src="https://dummyimage.com/300/000/fff">
    <h6> Hello World </h6>
  </div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kameron