CSS Grids – The New Hotness

A new technology is coming to browsers via CSS grids.

Presentation

This presentation does a fairly decent job at covering the important details (skip to 12:42):

Notes

  • Grid support is available in all major modern browsers.
  • Grid relies only on CSS and HTML, no JavaScript or anything else is needed.
  • Grids cut down on a lot of superfluous HTML and CSS (ex. Bootstrap classes, nests of divs, etc.).
  • Grids make it easier to arrange and rearrange content within a document.
  • Grids are defined by simply adding the declaration “display: grid;” to a CSS selector.
    • Example:
      .content {
        display: grid;
      }
  • Grids can be divided into columns with the property “grid-template-columns“, and rows with the property “grid-template-rows“.
    • Columns and rows support the new “fraction” (fr) value, in addition to em, px, %, etc.
      • Example:
        .content {
          display: grid;
          grid-template-columns: 2fr 1fr 2fr;
          grid-template-rows: auto 1fr 4fr;
        }
  • Grid columns/rows begin with a value of 1 at the top left, and increment in value going to down and to the right.
  • Placement of content can be done manually, by specifying number values within the “grid-column” and “grid-row” properties.
    • The number values are delimited by a forward slash (/).
      • Example:
        .header {
          grid-column: 1/4;
          grid-row: 2/3;
        }
  • Rather than memorize column and row numbers, grids can also use named template areas via the “grid-template-areas” property.
    • Example:
      .content {
        display: grid;
        grid-template-columns: 2fr 1fr 2fr;
        grid-template-rows: auto 1fr 4fr;
        grid-template-areas:
          "header header header"
          "main main main"
          "article article sidebar"
          "footer footer footer"
      }
  • Content can be placed within grid template areas via the “grid-area” property.
    • Example:
      header {
        grid-area: header;
      }
      #main-content {
        grid-area: main;
      }
      .article {
        grid-area: article;
      }
      .sidebar {
        grid-area:sidebar;
      }
      footer {
        grid-area: footer;
      }
  • Child elements do not inherit grids; allowing for nested grids that are unique.
  • @supports (display: grid;) { [...] } can be used to check if the browser supports grid.
  • @media screen and (min-width: <value>) { [...] } can be used in conjunction with grid to make dynamic and responsive layouts.

Additional Resources