0

The following is not my expected outcome

Specifically with justify-content: start - I do not want the extra space on the right.

justify-content: center:

justify-content: center

justify-content: start:

justify-content: start

How do I get the following display using Flex?

Note: The gap is standardised to 20px.

to flex left and align center

The "Hello" in the image is centered.

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 0 35px;
  background-color: grey;
}

.wrapper {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  /* issue */
  gap: 20px;
  border: 1px solid red;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid;
  width: 50px;
}
<div class="container">
  <div class="wrapper">
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
    <div class="box">Box 3</div>
    <div class="box">Box 4</div>
    <div class="box">Box 5</div>
    <div class="box">Box 6</div>
    <div class="box">Box 7</div>
    <div class="box">Box 8</div>
  </div>
  <p>Hello</p>
</div>

What I tried:

Removing extra spacing on a flexbox with wrapped children? This was not helpful because I have a standardized gap to follow, so in a sense, the centralization of the boxes has to be "recalculated" for every box that displays in the next row.

I hope I am clear about my issue.

tacoshy
  • 10,642
  • 5
  • 17
  • 34
Phobe
  • 1
  • 1
  • 1
    I would recommend the usage of CSS-Grid over Flexbox here. But a start would be to replace `align-items: center` with `align-items: space-between` – tacoshy Jun 07 '23 at 10:21

1 Answers1

0

The easiest way is the usage of CSS-Grid and a combination of auto-fit or auto-fill with minmax. It will create as many columns as needed or fitting with a minimum width while automatically resizing the element's width to adjust for remaining space:

.wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(50px, 1fr));
  gap: 20px;
  border: 1px solid red;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid;
}
<div class="container">
  <div class="wrapper">
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
    <div class="box">Box 3</div>
    <div class="box">Box 4</div>
    <div class="box">Box 5</div>
    <div class="box">Box 6</div>
    <div class="box">Box 7</div>
    <div class="box">Box 8</div>
    <div class="box">Box 9</div>
    <div class="box">Box 10</div>
    <div class="box">Box 11</div>
    <div class="box">Box 12</div>
    <div class="box">Box 13</div>
    <div class="box">Box 14</div>
    <div class="box">Box 15</div>
    <div class="box">Box 16</div>
    <div class="box">Box 17</div>
    <div class="box">Box 18</div>
    <div class="box">Box 19</div>
    <div class="box">Box 20</div>
  </div>
  <p>Hello</p>
</div>
tacoshy
  • 10,642
  • 5
  • 17
  • 34