Notes

Hands-on with CSS Grid Layout

Edit on GitHub

CSS & Sass
3 minutes
  • Defining a grid is as simple as adding layout: grid to an element.
1.wrapper {
2  display: grid;
3}

Defining templates

Rows and columns

1grid-template-columns: 1fr 1fr 1fr 1fr;
2grid-template-rows: auto 300px;

Areas

1grid-template-areas: 
2  "a a a a"
3  "b c d e"
4  "b c d e"
5  "f f f f";

or

1grid-template-areas:
2  "header header header header"
3  "nav main main sidebar";

Shorthand video

1grid-template: auto 300px / 1fr 1fr 1fr 1fr
2
3grid-template: 
4  "header header header header" auto // this is the first row, auto (size) is default, so it's okay if you don't mention it.
5  "nav main main sidebar" 300px // second row, the size for which is going to be 300px
6  / 1fr 1fr 1fr 1fr; // and the columns come at the end

the fr unit

  • Using fr avoids margin and padding issues. With % and em etc. it becomes a math equation when calculating grid-gap. If you used fr unit, it’ll automatically calculate both column and gutter sizes and adjust the size of the columns accordingly, plus there will be no bleeding gaps at the end either

See the Pen CSS Grid by example - 3A (fr vs. other units) by Aamnah Akram (@aamnah).

See the Pen CSS Grid by example - 3B (fr vs. other units) by Aamnah Akram (@aamnah).

  • fr is not truly responsive.

See the Pen CSS Grid by example - 4A (12 column grid, fr units) by Aamnah Akram (@aamnah) .

See the Pen CSS Grid by example - 4B (12 column grid, vw units) by Aamnah Akram (@aamnah).

  • You can mix and match relative and absolute units
1grid-template-columns: 2fr 1fr 300px;
2grid-gap: 1em;

repeat

  • Use repeat() if you’re using a pattern for columns. For example: grid-template-columns: repeat(12, 1fr) will give you a 12 column grid with every column of the equal size. grid-template-columns: repeat(3, 2fr 1fr); will give you 3 columns where each column has 2 columns inside, the sizes of the inside columns being 2fr and 1fr respectively.

See the Pen CSS Grid by example - using repeat() by Aamnah Akram (@aamnah).

Check browser support with @supports

  • Feature queries can determine if a CSS property is supported in the browser the site is ebing viewed in
1<p class="message">
2  You need a browser that supports CSS Grid Layout to see this example properly!  
3</p>
1@supports (display: grid) {
2  .message {
3    display: none;
4  }
5}

FYI, Safari (v10.0.3 on a fairly updated macOS Sierra v10.12.3 - the one i’m using right now: Sept 28, 2017) does not support display: grid. Support for Safari started v10.1 (released Mar 27, 2017) onwards.. High Sierra was just released yesterday and i haven’t updated because the minor changes aren’t that interesting to me can i use

See the Pen CSS Grid by example - check browser compatibility with @supports by Aamnah Akram (@aamnah).