1

What I have here is a container with background color and it contains multiple items that automatically align themselves when the screen is shrank.

Example with full width: https://i.stack.imgur.com/UbxtP.png

But when I shrink the width of the browser: https://i.stack.imgur.com/wyzzA.png

.flex-container {
  display: inline-flex;
  flex-wrap: wrap;
  background-color: DodgerBlue;
}

.flex-container > div {
  background-color: #f1f1f1;
  width: 100px;
  margin: 5px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}
<!DOCTYPE html>
<html>
  <body>

    <div class="flex-container">
      <div>1</div>
      <div>2</div>
      <div>3</div>  
      <div>4</div>
      <div>5</div>
      <div>6</div>  
      <div>7</div>
      <div>8</div>
    </div>

  </body>
</html>
Lanzy Erin
  • 33
  • 5

1 Answers1

0

If the width is fixed for your items, this particular case can be solved using CSS grid:

.wrapper {
  display:grid;
  grid-template-columns:repeat(auto-fit,100px); /* width of your item here */
  gap: 5px; /* the gap */
  margin:5px;
  /*justify-content:center uncomment this if you want to center everything  */
}

.flex-container {
  display: inline-flex;
  grid-column:1/-1; /* fill all the columns */
  max-width:max-content; /* restrict the width to the maximum number of items */
  gap: inherit; /* inherit the same gap */
  flex-wrap: wrap;
  background-color: DodgerBlue;
  outline:5px solid DodgerBlue;
}

.flex-container > div {
  background-color: #f1f1f1;
  width: 100px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}
<div class="wrapper">
  <div class="flex-container">
      <div>1</div>
      <div>2</div>
      <div>3</div>  
      <div>4</div>
      <div>5</div>
      <div>6</div>  
      <div>7</div>
      <div>8</div>
    </div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415