What is a grid container?
Learn the grid container with display: grid.
Grid container
CSS Grid begins by turning an element into a grid container. A single line is enough: display: grid. That declaration makes the direct children lay out as grid items; the browser arranges them into rows and columns.
Flexbox was one-dimensional; grid is two-dimensional: you control rows and columns at the same time. That makes it ideal for card layouts, dashboards and photo galleries.
Direct children become grid items
When you set display: grid on an element, only its direct children become grid items. Grandchildren stay unaffected; they keep their own inner layout.
This matches Flexbox behavior: the container is set, the children join the layout. If your markup has <div class="gallery"> holding dozens of <figure> elements, each one falls into a grid cell automatically.
When no template is set
If you set display: grid on a container but define no columns or rows, the browser stacks the children into a single column. Each item takes its own row; much like normal flow.
The real power comes with the grid-template-columns and grid-template-rows declarations you will meet in the next lessons. First open the container, then draw the template.
Exercise Make the gallery a grid container
Add a .gallery selector and write display: grid inside. The gallery becomes a grid container and its children turn into grid items.
Show example solution
/* add the gallery selector */
.gallery {
display: grid;
}
Test yourself
-
Which one turns an element into a grid container?
.gallery { display: ? }- display: grid
- grid: auto
- layout: grid
- container: grid
Show answer
display: grid — Correct. The display: grid declaration turns the element into a grid container and its children into grid items.
-
Make the gallery a grid container
.gallery { ____; }Show answer
.gallery { display: grid; } -
Match the concepts
- display: grid
- Grid container
- grid item
- Child of container
- grid container
- Parent element
- two dimensions
- Rows and columns