-2

Apologies if this has been asked before but I couldn't find exactly the same question.

I have the following:

.main{
    display: inline-flex;
    flex-direction: row;
}
<div class = "main">
    <div class="sub-div">1 </div>
    <div class="sub-div">2 </div>
    <div class="sub-div">3 </div>
    <div class="sub-div">4 </div>
    <div class="sub-div">5 </div>
    <div class="sub-div">6 </div>
</div>

What this does is it displays all the divs in same line. But how can I divide the divs such that there will be 3 divs on top row and 3 divs on bottom row?

Additionally, if the screen size gets smaller, how can I divide the divs such that there will be 2 divs on top row, 2 on middle row, and 2 on last row?

Can I do it without changing HTML structure or using Javascript?

TylerH
  • 20,799
  • 66
  • 75
  • 101
CrazyCSGuy
  • 123
  • 1
  • 15
  • If you want to use `flex`, you need to allow `flex-wrap` (to break into multiple lines) and set a fixed `width` to your `sub0div` class. For different sizes based on screen, look for "media queries in css" – Bruno Monteiro Jul 01 '20 at 01:00
  • Does this answer your question? [How to make flexbox items the same size?](https://stackoverflow.com/questions/29503227/how-to-make-flexbox-items-the-same-size) – Marik Ishtar Jul 01 '20 at 01:08

2 Answers2

0

Use flex-wrap: wrap on .main to allow its children to wrap onto multiple lines. Then, you could explicitly set the width equal to calc(100% / n) where n is the number of children you want per row.

To change the layout from 2 divs per row to 3 divs per row, use a media query, as shown in the code snippet below.

.main {
  display: inline-flex;
  flex-wrap: wrap;
}

.sub-div {
  width: calc(100% / 2);
}

@media screen and (min-width: 600px) {
  .sub-div {
    width: calc(100% / 3);
  }
}
<div class="main">
  <div class="sub-div">1 </div>
  <div class="sub-div">2 </div>
  <div class="sub-div">3 </div>
  <div class="sub-div">4 </div>
  <div class="sub-div">5 </div>
  <div class="sub-div">6 </div>
</div>
khan
  • 1,466
  • 8
  • 19
0

You may achieve it with Grid and media query.

.main {
  display: grid;
  /* grid-gap: 50px 100px; */
  grid-template-columns: auto auto auto;
}

@media only screen and (max-width: 768px) {
  .main {
    grid-template-columns: auto auto;
  }
}
<div class="main">
  <div class="sub-div">1 </div>
  <div class="sub-div">2 </div>
  <div class="sub-div">3 </div>
  <div class="sub-div">4 </div>
  <div class="sub-div">5 </div>
  <div class="sub-div">6 </div>
</div>
yinsweet
  • 2,823
  • 1
  • 9
  • 21