Yaron
Yaron

Reputation: 2749

Creating responsive grid with FlexBox

I'm having a real complicated situation that I'm trying to resolve.
I try to create a 2 columns (maximum) layout on bigger displays and 1 column on small display (Smaller than 450px).

I have no simple way to explain so here some images:

2 Columns Layout

1 Column Layout

I manage to accomplish the 2-columns display with the following css.

.breeding-row {
       /* equal height of the children */
           display: flex;
  }

  .breeding-col {
         /* additionally, equal width */
        flex: 1;
        padding: 0;
        border: none;
   }

   @media only screen and (max-width: 450px) {
           .breeding-col {
                  flex-basis: 100%;
            }
           .breeding-row {
               flex-direction: column;
             }
    }

    @media only screen and (min-width: 450px) {
        .breeding-col {
                flex-basis: 50%;
          }
     }

This works great for 2 columns. But when it becomes 1 column the cells, obviously, positioned one after another and I get...

enter image description here

I'm trying to think of something that will work for both 1 and 2 columns display and will give me the 1 column expected result... I will highly appreciate any suggestion.

Upvotes: 1

Views: 184

Answers (1)

Asons
Asons

Reputation: 87292

You use the order property to change their order on smaller screens.

In combination with a media query you can do like this, where you make the even children (2 and 4) get order: 1 (the default is 0) when screen goes below 600px, and together with changing the flex direction to column and they will stack on top of each other.

As the default value of align-items is stretch, the items will have the same height per row.

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

.flex div {
  flex-basis: calc(50% - 20px);
  margin: 10px;
  background: blue;
}

.flex div:nth-child(odd) {
  background: red;
}

@media (max-width: 600px) {
  .flex {
    flex-direction: column;
  }
  .flex div {
    flex-basis: auto;
  }
  .flex div:nth-child(even) {
    order: 1;
  }
}
<div class="flex">
  <div>R1<br>R1<br>R1<br>R1<br>R1<br></div>
  <div>B1</div>
  <div>R2</div>
  <div>B2<br>B2<br>B2<br></div>
</div>


You can also keep the flex direction as row, and change the flex-basis to 100%

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

.flex div {
  flex-basis: calc(50% - 20px);
  margin: 10px;
  background: blue;
}

.flex div:nth-child(odd) {
  background: red;
}

@media (max-width: 600px) {
  .flex div {
    flex-basis: 100%;
  }
  .flex div:nth-child(even) {
    order: 1;
  }
}
<div class="flex">
  <div>R1<br>R1<br>R1<br>R1<br>R1<br></div>
  <div>B1</div>
  <div>R2</div>
  <div>B2<br>B2<br>B2<br></div>
</div>

Upvotes: 1

Related Questions