Home > Back-end >  How to make horizontal boxes auto stack vertically based on screen width?
How to make horizontal boxes auto stack vertically based on screen width?

Time:01-11

I have this simple boxes inside a bordered frame, the frame has a max width.

.outer {
  display: flex;
  max-width: 1000px;
  border: 1px solid black;
}

.inner {
  min-width: 100px;
  height: 100px;
  background-color: blue;
  margin: 10px;
  color: white;
}
<div class='outer'>

  <div class='inner'>1</div>
  <div class='inner'>2</div>
  <div class='inner'>3</div>
  <div class='inner'>4</div>
  <div class='inner'>5</div>
  <div class='inner'>6</div>
  <div class='inner'>7</div>
  
</div>

You can see as screen width reduces, the boxes get out of the frame. My question is, can those boxes automatically stack vertically inside the frame, so when screen width reduces, 7 goes under 1, then 6 under 1, 7 under 2, then 5 under 1, 6 under 2, 7 under 3, etc.

When screen width reduces to a minimum, just 1 column remains, follow 1, 2, 3, 4, 5, 6, 7 vertically.

In real app I have random number of boxes, so the stack needs to be automatic.

CodePudding user response:

I think you're looking for flex-wrap: wrap;

.outer {
  display: flex;
  max-width: 1000px;
  border: 1px solid black;
  flex-wrap: wrap;
}

.inner {
  min-width: 100px;
  height: 100px;
  background-color: blue;
  margin: 10px;
  color: white;
}
<div class='outer'>

  <div class='inner'>1</div>
  <div class='inner'>2</div>
  <div class='inner'>3</div>
  <div class='inner'>4</div>
  <div class='inner'>5</div>
  <div class='inner'>6</div>
  <div class='inner'>7</div>
  
</div>

CodePudding user response:

to make flex boxes be columns, use the CSS

flex-direction: column;

You can find this and more from my source:

https://www.w3schools.com/css/css3_flexbox_container.asp

CodePudding user response:

This issue can and should be solved with CSS-Grid. This ensures that the columns are respected in every case and that the container will utilize the full width and not remain a white space caused by the flex-wrap (which is the major downside of @Libra's answer).

You can make use of the auto-fit and minmax values. This will ensure that an element has a minimum width and will occupy the rest. It will then fit as many elements next to each other as possible and push the other elements to the next rows but respect the columns:

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}

/* for visualization purpsoe only */
.container {
  gap: 0.5em;
}

.container > div {
  display: flex;
  justify-content: center;
  align-items: center;
  aspect-ratio: 1;
  background: blue;
  font-size: 2em;
  color: white;
}
<div >
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
</div>

  • Related