How can I make my "display: grid" responsive using media queries for mobile devices and tablets?

27 Views Asked by At

Grid desktop view I want to make this grid desktop view responsive on mobile devices using media queries in my CSS. It's perfectly positioned in desktop but it's not responsive on mobile and tablets.

.grid-container {
    display: grid;
    grid-template-columns: auto auto auto auto auto;
    gap: 25px;
}

/** Media Queries **/
@media screen and(max-width: 400px) {
    .grid-container {
        grid-template-columns: auto;
    }
    .grid-container .item-1 {
        grid-column: 1 / span 5;
        grid-row: 1;
    }
}

I created a grid with 5 columns for 5 different items (card). Then Item 1 spans the first three columns. Item 3 span from row 1 - 3 and Item 5 span from column 2 - 5.

.item-1 {
    grid-column: 1 / span 3;
    grid-row: 1;
    height: auto;
    background-color: hsl(263, 55%, 52%);
    position: relative;
}
.card-detail {
    position: absolute;
    top: 59px;
}

.item-3 {
    grid-column-start: 5;
    grid-row-start: 1;
    grid-column-end: 6;
    grid-row-end: 3;
    background-color: hsl(0, 0%, 100%);
}

.item-5 {
    grid-column-start: 2;
    grid-column-end: 5;
    background-color: hsl(219, 29%, 14%);
    color: hsl(0, 0%, 100%);
}

I want the width of each grid item to span a width of 100% on mobile devices. On tablets I want the grid items to span 50% (that's 2 items in each row).

1

There are 1 best solutions below

0
tacoshy On

Grid has the huge advantage of not requiring media queries to make the grid responsive. Using auto-fit or auto-fill in combination with minmax will adapt the number of columns depending on the screen on its own:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  grid-gap: 1em;
}

/* for visualization only */
.grid > div {
  border: 2px dashed red;
  min-height: 20vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="grid">
  <div>Box 1</div>
  <div>Box 2</div>
  <div>Box 3</div>
  <div>Box 4</div>
  <div>Box 5</div>
</div>

However, if you really want a strict 1-column mobile and 2-column desktop layout then you can go with media queries such as this:

.grid {
  display: grid;
  grid-gap: 1em;
}

@media only screen and (min-width: 720px) {
  .grid {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .grid > div:nth-child(4n + 2),
  .grid > div:nth-child(4n + 3) {
    grid-column: span 2;
  }
}

/* for visualization only */
.grid > div {
  border: 2px dashed red;
  min-height: 20vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="grid">
  <div>Box 1</div>
  <div>Box 2</div>
  <div>Box 3</div>
  <div>Box 4</div>
  <div>Box 5</div>
  <div>Box 6</div>
  <div>Box 7</div>
  <div>Box 8</div>
  <div>Box 9</div>
</div>

You should make use of the nth-child() selector in addition to using simply grid-column: span 2