Search code examples
htmlcsscss-grid

css grid layout for tablet


I have 3 divs that I am showing in a row using css grid layout for desktops. For phone, I am showing 1 div per row. For tablets (min-width:768px), I want only the first div to appear on the first row. And the other two divs on second row side by side. But I can't figure out how to do that in the grid layout using grid-template columns. Any help will be much appreciated. Here's a simpler version of my code:

.outer {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}


/** media queries for phones and up*/

@media only screen and (min-width:320px) and (max-width:767px) {
  .outer {
    grid-template-columns: repeat (1, 1fr);
  }
}


/** media queries for tablets*/

@media only screen and (min-width:768px) {
  .outer {}
}
<div class="outer">

  <div class="inner">
    <p>I am div 1</p>
  </div>

  <div class="inner">
    <p>I am div 2</p>
  </div>

  <div class="inner">
    <p>I am div 3</p>
  </div>

</div>


Solution

  • You want grid-template-columns: 1fr 1fr; to set the grid layout to 2 columns, and you want to get the first div to take the space of 2 columns, and the rest 1 column each. You can do this many ways, but I think the one that makes most sense is to select the .inner:first-child to get the first div and set it to grid-column: 1 / span 2;. This makes the selected element take the space of a span of 2 columns, starting from the 1st column, which is what you want.

    .outer {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
    }
    
    
    /** media queries for phones and up*/
    
    @media only screen and (min-width:320px) and (max-width:767px) {
      .outer {
        grid-template-columns: 1fr;
      }
    }
    
    
    /** media queries for tablets*/
    
    @media only screen and (min-width:768px) {
      .outer {
        grid-template-columns: 1fr 1fr;
      }
      .inner:first-child {
        grid-column: 1 / span 2;
      }
    }
    <div class="outer">
    
      <div class="inner">
        <p>I am div 1</p>
      </div>
    
      <div class="inner">
        <p>I am div 2</p>
      </div>
    
      <div class="inner">
        <p>I am div 3</p>
      </div>
    
    </div>