CSS Grid
CSS Grid places elements in rows and columns at the same time. You switch it on for the parent element with display: grid and describe the columns in one property.
Syntax
.container {
display: grid;
grid-template-columns: 200px 1fr 1fr;
gap: 16px;
}
.item { grid-column: 1 / 3; } Key properties and functions
| Item | What it does |
|---|---|
display: grid | makes the element a grid container; its direct children become grid items |
grid-template-columns | the grid's columns: how many and how wide |
grid-template-rows | row heights (by default, sized to content) |
fr | a "share of free space" unit: 1fr 2fr splits it 1 : 2 |
repeat() | repetition: repeat(3, 1fr) gives three equal columns |
minmax() | size limits for a column: minmax(140px, 1fr) is never narrower than 140px |
auto-fill / auto-fit | as many columns as fit; auto-fit also stretches them into empty space |
gap | gaps between rows and columns |
grid-column / grid-row | how many columns or rows an item spans: span 2 or 1 / 3 |
Example
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 12px;
}
.grid div {
padding: 12px;
background: #e0f2fe;
border: 1px solid #0284c7;
}
.wide {
grid-column: span 2;
} <div class="grid">
<div class="wide">1 (span 2)</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div> Result
Good to know
- repeat(auto-fill, minmax(140px, 1fr)) is a responsive grid without a single media query: there are fewer columns as the window gets narrower.
- Grid is for two-dimensional layouts (a page grid, a gallery); flexbox is for one direction (a menu, a row of buttons). They are often combined.
- Items are placed into cells automatically; grid-column and grid-row are only needed when an item has to take a specific place or several cells.
Sources and specification
- MDN: Basic concepts of grid layout — MDN Web Docs
- CSS Grid Layout Module Level 1 (W3C) — W3C
See also
The gap property
The CSS gap property sets the space between items of a flex or grid container without extra margins: one or two values, row-gap and column-gap.
The grid-template-columns property
The CSS grid-template-columns property defines the columns of a grid: px, %, fr, repeat(), minmax() and auto-fill/auto-fit for a responsive grid.
The display property
The CSS display property sets how an element takes part in layout: as a block, inline with text, as a flex or grid container, or not at all. Values, examples.
Media queries (@media)
CSS media queries (@media) apply styles depending on screen width, orientation and user settings: min-width, max-width, mobile-first and common mistakes.
Responsive CSS Grid cards
A card grid that adapts its column count to screen width, with no media queries.
CSS Flexbox for beginners
A beginner's guide to CSS Flexbox: display: flex, axes, justify-content, align-items, flex-wrap, gap and flex: 1, with examples of a menu, cards and centering.