CSS Grid order on different @media widths

Viewed 56

My first post. I've seen that there are a few similar questions, but none seem to have the answer I'm looking for (if at all).

I have a simple 4 row, 1 column grid.

  • On screens smaller than 768px I want the row order to be: Menu, Header, Main, Footer
  • On larger screens, I want the row order to be: Header, Menu, Main Footer
  • (basically, switch Menu and Header on different devices)

The colours change when resizing (assigned to their appropriate grid (ie. Header changes from turquoise to palevioletred)), but the row order does not.

@media only screen and (max-width: 767px) {
    body {
        display: grid;
        grid-template-areas:
            'menu'
            'header'
            'main'
            'footer'
            ;
    }

    .gridMenu {
        background: lightcoral;
    }
    .gridHeader {
        background: turquoise;
    }
    .gridMain {
        background: lightsalmon;
    }
    .gridFooter {
        background: pink;
    }
}

/* Tablet - Portrait */
@media only screen and (min-width: 768px) {
    /* Grid */

    body {
        display: grid;
        grid-template-areas:
            'header'
            'menu'
            'main'
            'footer'
            ;
    }

    .gridMenu {
        background: palegreen;
    }
    .gridHeader {
        background: palevioletred;
    }
    .gridMain {
        background: lightskyblue;
    }
    .gridFooter {
        background: cornflowerblue;
    }
}
<body>
    <div class="gridMenu">
        Menu Here
    </div>
    <div class="gridHeader">
        Header Here
    </div>
    <div class="gridMain">
        Main Here
    </div>
    <div class="gridFooter">
        Footer Here
    </div>
</body>

Any advice will be greatly appreciated.

Thanks.

1 Answers

Mistake: You just failed to declare grid-area, Let CSS know which div to put where. Also remove unwanted @media query and duplicate CSS properties.

Here's your corrected CSS

body {
  display: grid;
  grid-template-areas:
    'menu'
    'header'
    'main'
    'footer'
  ;
}

.gridMenu {
  grid-area: menu;
  background: lightcoral;
}

.gridHeader {
  grid-area: header;
  background: turquoise;
}

.gridMain {
  grid-area: main;
  background: lightsalmon;
}

.gridFooter {
  grid-area: footer;
  background: pink;
}


/* Tablet - Portrait */
@media only screen and (min-width: 768px) {
  /* Grid */
  /* Add only the things you wish to modify */

  body {
    grid-template-areas:
      'header'
      'menu'
      'main'
      'footer'
    ;
  }

  .gridMenu {
    background: palegreen;
  }

  .gridHeader {
    background: palevioletred;
  }

  .gridMain {
    background: lightskyblue;
  }

  .gridFooter {
    background: cornflowerblue;
  }
}


Related