Change from Grid Layout to Flex Layout with Responsive

Issue

I would like to have 3 elements arranged based on the media resolution. On Desktop I would like them to be

box1  box2
      box3

and in responsive mode on mobile (max-width: 800px) I would like them to be

box1
box2
box3

For this I thought I need in my code to have in the general section

  .box-container {
    display: grid;
    grid-template-columns: 60% 40%;
    grid-auto-flow: column;
  }

and

  .box1 {
    grid-row: 1 / 3;
    background: lightblue;
  }

with this changing in the media query section by overwriting this with

  @media only screen and (max-width: 800px) {
    .box-container {
      display: flex;
      grid-template-columns: 100%;
      flex-direction: column;
    }
  }

However somehow this is not overwritten and elements stay in Grid view. When I put this code in the general section the boxes show up below each other.

https://codepen.io/tobwun/pen/MWQOpjL

Thanks for any help!

Toby

Solution

Just reverse the order of your .box-container CSS rules. Put the grid rule first, then the flex rule with the media query after it.

.box-container {
  display: grid;
  grid-template-columns: 60% 40%;
  grid-auto-flow: column;
}

@media only screen and (max-width: 800px) {
  .box-container {
    display: flex;
    flex-direction: column;
  }
}

And in future, include a snippet in your question — it’s Stack Overflow’s version of a Codepen or jsFiddle.

 .mydiv {
    height: 45%;
    background: #2f8466;
    color: white;
  }

  .box-container {
    display: grid;
    grid-template-columns: 60% 40%;
    grid-auto-flow: column;
  }

  @media only screen and (max-width: 800px) {
    .box-container {
      display: flex;
      grid-template-columns: 100%;
      flex-direction: column;
    }
  }

  .box1 {
    grid-row: 1 / 3;
    background: lightblue;
  }

  .box2 {
    background: lightgreen;
  }

  .box3 {
    background: lightyellow;
  }
  
  
<body>

  <div class="main" id="main1">
    Grid Layout Changes To Flex Layout
    <div class="box-container">
      <div class="box1">
        Text1
      </div>
      <div class="box2">
        Text2
      </div>
      <div class="box3">
        Text3
      </div>
    </div>
  </div>

</body>

Answered By – Brett Donald

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.