2 min read

CSS Grid Layout

CSS Grid Layout is a two-dimensional layout system for the web. It lets you lay out items in rows and columns. It has many capabilities that allow for complex layouts to be built straightforwardly.

1. The Concept

Flexbox is designed for one-dimensional layouts (either a row OR a column). Grid is designed for two-dimensional layouts (rows AND columns at the same time).

2. The Grid Container

To start using Grid, you define a container element as a grid with display: grid.

.container {
  display: grid;
  /* or inline-grid */
}

Defining Columns and Rows

You define the columns and rows of the grid with grid-template-columns and grid-template-rows.

.container {
  display: grid;
  grid-template-columns: 100px 200px auto; /* 3 columns */
  grid-template-rows: 50px 150px; /* 2 rows */
}

The fr Unit

The fr unit represents a fraction of the available space in the grid container.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
}

repeat() Function

Used to repeat columns or rows.

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* Same as 1fr 1fr 1fr */
}

Grid Gap

The gap property (formerly grid-gap) defines the size of the gap between the rows and columns.

.container {
  gap: 20px; /* 20px gap between rows and columns */
  /* row-gap: 20px; column-gap: 50px; */
}

3. Placing Items

You can place items onto the grid using line numbers.

.item1 {
  grid-column-start: 1;
  grid-column-end: 3; /* Spans from line 1 to line 3 (2 columns) */
  grid-row-start: 1;
  grid-row-end: 3;
}

Shorthand: grid-column: 1 / 3;

span Keyword

You can specify how many columns/rows an item should span.

.item1 {
  grid-column: span 2;
}

4. Grid Areas

You can name grid items and then reference them in the container to create a layout map.

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }

.container {
  display: grid;
  grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";
}

5. Alignment

Grid has powerful alignment properties similar to Flexbox.

  • justify-items: Aligns items horizontally inside their cell (start, end, center, stretch).
  • align-items: Aligns items vertically inside their cell (start, end, center, stretch).
  • justify-content: Aligns the whole grid horizontally within the container.
  • align-content: Aligns the whole grid vertically within the container.

programming/css/css programming/css/css3 programming/css/flexbox programming/css/grid-template-areas