Jump to Categories

CSS Grid

// HTML
<div class="site">

    <h1 class="header"></h1>

    <div class="main"></div>

    <div class="sidebar"></div>

    <div class="footer"></div>

</div>
// CSS
.site {
  display: grid;
  grid-template-columns: 100%;
  grid-template-rows: auto;
  grid-template-areas:
    "header"
    "main"
    "sidebar"
    "footer";
  margin: 0 auto;
  max-width: 800px;
}

@media screen and (min-width: 600px) {
  
    .site {
      display: grid;
      grid-template-columns: 1fr 2fr;
      grid-template-rows: auto;
      grid-template-areas:
        "main sidebar"
        "header header"
        "footer footer";
      margin: 0 auto;
      max-width: 800px;
    } 
  
}

.main, .sidebar, .footer {
  background: red;
  height: 100px;
}

.main {
  grid-area: main;
}

.header {
  grid-area: header;
}

.sidebar {
  background: yellow;
  grid-area: sidebar;
}

.footer {
  background: blue;
  grid-area: footer;
}

See the Pen CSS Grid by Shane Prendergast (@webknit) on CodePen.

Minmax

grid-template-columns: minmax(100px, 1fr) minmax(100px, 1fr);

Auto fill

grid-template-columns: repeat(auto-fill, minmax(100px, 200px));

Auto fit (best solution)
Similar to autofill but won't display empty columns like the above, will auto collapse empty cols to 0 pixels, only apparent when using repeat and minmax

grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));

Process

  • Build accessible mobile-first layout without grid
  • Use mobile-first layout as fallback for all browsers
  • Use @supports to detect grid support
  • At the appropriate breakpoint, create layout with grid and grid-areas
  • Explore new layouts as viewport widens

References