Search code examples
htmlcssmedia-queriescss-grid

CSS grid and responsive view


I just started learning the CSS grid today, and I can start seeing the point to use this awesome css classes. But one thing that really is confusing me, is how to reorganize the grid on mobile devices.

I made an example below here. That is working how it should on a desktop view. When the screen size is going below 991px. I would like the grid was looking like this:

enter image description here

But how should I control that using the CSS grid?

.wrapper {
  display:grid;
  grid-template-columns:1fr 2fr 1fr;
  grid-auto-rows:minmax(100px,auto);
  grid-gap:1em;
}	

.wrapper > div {
  background-color: #eee;
  padding: 1em;
}
.wrapper > div:nth-child(odd) {
  background-color: #ddd;
}

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

.box2 {
  grid-column:3;
}

.box3 {
  grid-column:3;
}
<div class="wrapper">
  	<div class="box box1">Box 1</div>
    <div class="box box2">Box 2</div>
    <div class="box box3">Box 3</div>
</div>


Solution

  • You should use @media and you need to make again adjustments for 991px.

    .wrapper {
      display:grid;
      grid-template-columns:1fr 2fr 1fr;
      grid-auto-rows:minmax(100px,auto);
      grid-gap:1em;
    }	
    
    .wrapper > div {
      background-color: #eee;
      padding: 1em;
    }
    .wrapper > div:nth-child(odd) {
      background-color: #ddd;
    }
    
    .box1 {
      grid-column:1/3;
      grid-row:1/3;
    }
    
    .box2 {
      grid-column:3;
    }
    
    .box3 {
      grid-column:3;
    }
    
    @media screen and (max-width:991px){
    
      .wrapper {
        grid-template-columns:1fr 1fr;
      }	
      .box1 {
        grid-column:1/4;
        grid-row:1/3;
      }
    
      .box2 {
        grid-column:1/2;
      }
    
      .box3 {
        grid-column:2/4;
      }
      
    }
    <div class="wrapper">
      	<div class="box box1">Box 1</div>
        <div class="box box2">Box 2</div>
        <div class="box box3">Box 3</div>
    </div>