CSS: Grid Layout

By Xah Lee. Date: . Last updated: .

What is grid layout

Grid Layout is layout system that creates layout based on rectangular grid, in a flexable and dynamic way.

First you set a element's display property to display: grid.

then you define the lengths between vertical grid lines (columns) and horizontal grid lines (rows), by using grid-template-columns and grid-template-rows. This gives you a grid of lines that is the foundation of your layout.

Then you define how child items fill the cells or areas (neighboring cells) between grid lines, by using grid-row, grid-column or grid-area. A child item may occupy more than one grid cells.

here's a typical grid layout for website home page:

header
main. good morn.

the complete code is:

<div class="xgrid-main-RrpYB">
 <div class="header">header</div>
 <div class="main">main. good morn.</div>
 <div class="sidebar">sidebar</div>
 <div class="footer">footer</div>
</div>
.xgrid-main-RrpYB {
 display: grid;
 grid-template-columns: 1fr 4fr;
 grid-template-rows: auto auto auto;
 margin: 15px;
 gap: 1px;
 grid-template-areas:
  "a a"
  "b c"
  "d d";
 > * {
  border: solid 2px silver;
 }
 > .main {
  grid-area: c;
  height: 60px;
 }
 > .header {
  grid-area: a;
 }
 > .sidebar {
  grid-area: b;
 }
 > .footer {
  grid-area: d;
 }
}

The grid container

To create a grid layout, set a element's Display Property to display: grid or display: inline-grid.

Its direct children are grid items. They are the contents of the grid.

example

by default, items are made into rows.

1
2
3
4
<div class="xgrid-nil54">
 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
</div>
.xgrid-nil54 {
 display: grid;
 > div {
  border: solid 1px grey;
 }
}

Define grid shape

Define child item position and span.

Implicit grid

Total number of explicit grid cells is equal to row count times column count.

extra items become rows

if you have more items than your explicit grid cells, the extra items become rows by default, and is called implicit grid.

1
2
3
4
5 extra
6 extra
<div class="xgrid-extra-kFNk4">
 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
 <div>5 extra</div>
 <div>6 extra</div>
</div>
.xgrid-extra-kFNk4 {
 display: grid;
 grid-template-columns: 1fr 1fr;
 grid-template-rows: 1fr 1fr;
 > div {
  border: solid 1px grey;
 }
}

Browser support

supported by all major browsers since 2017.

CSS grid layout

CSS. Layout