[CSS] Grid

Intro

A good video to watch: https://www.youtube.com/watch?v=7kVeCqQCxlk

Grid terminology

  • Grid container: Element containing a grid, defined by setting display: grid.
  • Grid item: Element that is a direct descendant of the grid container.
  • Grid line: Grid lines are referenced by number, starting and ending with the outer borders of the grid. Starting from 1
  • Grid cell
  • Grid track: The space between two or more adjacent grid lines. Row tracks are horizontal, column tracks are vertical.
  • Grid area: Rectangular area between four specified grid lines. Can cover one or more cells.
  • Grid gap: Empty space between grid tracks. Commonly called gutters
1
2
3
4
5
6
7
<div class = "site">
<header class="masthead"></header>
<h1 class="page-title"></h1>
<main class="main-content"></main>
<aside class="sidebar"></aside>
<footer class="footer"></footer>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
.site {
display: grid;
/*
Draw grid lines. Takes list of length values(em, px, %, fr(fraction)) denoting the distance between each line.
Grid items automatically populate grid from top left to bottom right based on HTML source order
*/
grid-template-columns: 2fr 1fr 1fr;
grid-template-rows: auto 1fr 3fr;
}
.masthead {
/*
Applied to grid items. Defines the start and end grid lines for columns and rows.
*/
grid-column: 2/4; /* From column line 2 to column line 4 */
grid-row: 2/3;
}

.page-title {
grid-column: 1/4;
grid-row: 1/2;
}

.main-content {
grid-column: 1/2;
grid-row: 2/4;
}

To make grid more responsive, we use grid-template-areas. Applied to grid container. Uses a text-based grid map to apply grid area names to individual cells. Then, use grid-area: [area-name]; to specify what grid area the element is placed within.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.site {
grid-template-areas:
"title title title"
"main header header"
"main sidebar footer";
}

.masthead {
grid-area: header;
}

.page-title {
grid-area: title;
}

.main-content {
grid-area: main;
}

.sidebar {
grid-area: sidebar;
}

Neted grids

Grids are not inherited by child elements. Instead we create nested grids.

Browser Support

Use feature queries to test for grid support in the current browser. @supports (displahy: grid) {...}.

CSS Grid approach:

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

[Appendix]

  • Firefox has a great grid detector.
  • Rachel Andrew’s Grid by Example
  • CSS Tricks
  • example