From Flex to Grid#
CSS grid layout—which everyone just calls grid—is a
-
A Complete Guide to Grid – CSS Tricks
The grid version of the flexbox classic. -
CSS Grid Layout: A New Layout Module for the Web
WebKit (Safari’s) overview, from 2017. -
Basic Concepts of Grid Layout - MDN
Back to MDN. -
Basics of CSS Grid
From web guru Jen Simmons. -
Flexbox vs. CSS Grid
Jen unpacks when to use each regime. -
Grid by Example
Loads of examples. -
Grid Garden
Like the Froggy game, but for grid.
We had some of this two-dimensionality with flex-wrapdisplay: grid;display: inline-grid;
Grid truly supplants many of the previous box model layout approaches (like float ,margin
There are many novel, powerful uses for grid—it is really the backbone of modern web layout!
As in nature, systems of order govern the growth and structure of animate and inanimate matter.
So human activity itself has, since the earliest times, been distinguished by the quest for order.
Grid Concepts#
New Terminology#
Grid introduces some new vocabulary:
-
Line
-
The dividing lines that define the grid, vertical or horizontal. (Think gutters.)
-
Track
-
The horizontal or vertical space between the lines. (Think rows and columns.)
-
Cell
-
The intersection of a horizontal and vertical track. This is different from a grid item—the cell is the spot/placement, the item is the actual element—since as you’ll see, you can position items in an arbitrary cell.
-
Area
-
You can combine one or more adjacent grid cells into a rectangular area. Often you give these a subjective name, for convenience/ergonomics.
New Units and Functions#
Grid also introduces some specific new length units:
-
fr -
This new unit represents a fraction of the available space in the grid container—usually,
(width). This is very similar to using whole numbers ininline-size It is very handy; you’ll use it a lot with grid:flex-basis..two-to-one { display: grid; grid-template-columns: 2fr 1fr; } -
min-content -
The intrinsic minimum size of an element. With text, this is the longest single word:
.narrow-sidebar { display: grid; grid-template-columns: 1fr min-content; } -
max-content -
Same for the maximum. With text, this is the whole sentence/line:
.wider-sidebar { display: grid; grid-template-columns: 1fr max-content; } -
fit-content -
A combo of the min/max. Uses the available space—but never less than
and never more thanmin-contentmax-content:.fit-sidebar { display: grid; grid-template-columns: 1fr fit-content; }You can use these last three values in grid properties (
min-, andmax-, ), as we’ll see below—but they are also usable anywhere length units work—likefit-content orinline-sizeblock-size.
…and also functions to use the units:
-
minmax() -
A function that defines a range for a track—setting a minimum and maximum length together. These are really useful for setting reasonable limits on responsive grid designs:
.flexible-sidebar { display: grid; grid-template-columns: 1fr minmax(12rem, 25rem); } -
repeat() -
This function repeats a track list, so you don’t have to write it over and over:
.twelve-columns { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr; /* How many columns is this? 👆 */ } .also-twelve-columns { display: grid; grid-template-columns: repeat(12, 1fr); /* Much better. */ }
…shorthand?#
Grid also has some shorthand properties, but again we would avoid them! And they’re less commonly used, because of the complexity of the layout system.
Container (Parent) Properties#
display: grid; #
display: grid;Again, grid is a lot like flex—it starts with display: grid;
Same as flex, there is also display: inline-grid; —
grid-template-columns / grid-template-rows #
grid-template-columnsgrid-template-rowsSetting display: grid;grid-template-columns ,grid-template-rows ,
– MDNgrid-template-columns – MDNgrid-template-rows
Define your tracks.
Notice in the second example, the items do not wrap to a new column—because grid-auto-flow: row;column
Again like flex, there is similar behavior on the horizontal/vertical axes—with the defaults around horizontal/row based behavior since width is usually our constraint (with pages scrolling vertically).
So for many uses, you will only need to specify your column structure—leaving the rows to create themselves, as needed. This is called an implicit grid (vs. an explicit grid that we set/define):
Drag that divider! The additional rows are automatically added, as needed. Note that they size vertically to their largest content!
grid-auto-columns / grid-auto-rows #
grid-auto-columnsgrid-auto-rowsBy default, these implicit grid tracks are sized autogrid-auto-rows :
– MDNgrid-auto-columns – MDNgrid-auto-rows
Lets the content create the tracks.
The perpendicular grid-auto-columnsgrid-auto-flow: column;
gap / column-gap / row-gap #
gapcolumn-gaprow-gapGrid also shares the gap ,column-gap ,row-gap
– MDNgap – MDNcolumn-gap – MDNrow-gap
The exact same as with flex!
You rarely see a gridgap .
justify-items #
justify-itemsAlso like flex (there’s a pattern here), we can position items within the tracks—but now we have control over both axes and the overall placement. To start, justify-items
justify-items
This only works with grid.
The terminology here is always a bit confusing, but think of it this way—in grid, the main axis is always the horizontal row. So justify always means left/right, and align always means top/bottom. Easier to remember than flex! No flipping axes:
align-items #
align-itemsAnd align-items
align-items
Same as flex, again!
Note that there isn’t any change on the last implicit row with the default auto /
There are also baseline
justify-content / align-content #
justify-contentalign-contentIf the total size of your grid is less than the container (because of your explicit column or row sizes), you can set the overall justification and alignment within the grid container:
– MDNjustify-content – MDNalign-content
When there is extra space.
Again, this is just like flex! Same syntax, same behavior—you get the idea. Grid is like Flex+.
Less Like Flex#
Okay, so far this is mostly like flex! To the point where you can often use them interchangeably for some layouts. You get it.
But now let’s look at where grid offers more specific and powerful control.
Using repeat() #
repeat()Grid’s repeat
repeat()
Remember, D.R.Y!
The ()calc() )
Notice that the items always stick to the grid structure—independent of their content—unlike our previous flex-wrap
Flex is sometimes referred to in this way as content-out, while grid is a layout-in system.
auto-fill / auto-fit #
auto-fillauto-fitYou can also use the repeatauto-fillauto-fit
- Auto-Sizing Columns in CSS Grid – CSS Tricks
Better than MDN, for this.
Drag the divider over to see the difference in auto-fill /auto-fit
grid-template-areas #
grid-template-areasGrid is really useful for scaffolding out layouts, and sometimes it is helpful to give your grid areas qualitative/descriptive names that reflect their usage. This also makes it possible for the grid items (children) to reference them, below.
grid-template-areas
These are grid’s real designer superpower.
This is done with a bit of ASCII art to reflect the layout! Repeating the name of a grid area makes the content span those cells. The syntax itself then provides an ergonomic visualization of the grid structure (for us humans):
You can also name grid lines with [linename] length
section {
display: grid;
grid-template-columns: 2fr 1fr;
grid-template-areas:
'intro intro '
'copy sidebar'
'legal sidebar';
}
Item (Child) Properties#
You can really start to see the power of grid when you use these properties on the individual grid items (children) within the containers. While the container (parent) properties usually make for uniform layouts, item (child) properties allow for unique structures.
grid-area #
grid-areaIf you’ve defined grid-template-areas
grid-area
These go on the items/children.
These grid-area
This is the kind of common layout that was unnecessarily hard before grid! It’s so much easier now.
grid-column / grid-row #
grid-columngrid-rowYou can also control item placement in unnamed (and implicit) grid areas with the grid-columngrid-row
– MDNgrid-column – MDNgrid-row
Where should the item go?
These take two values, divided with a /span
Notice that we can leave off the end line if it doesn’t spanspan
These are technically shorthand properties, but we’ll allow it here—they are easier to read!
span / dense #
spandenseYou can also leave off the start line if you just want to specify a span ,
We’ve added grid-auto-flow: dense;
Implicit Tracks#
And if you specify non-contiguous rows or columns, grid will dutifully create as many implicit tracks as it needs to accommodate them—even if they are empty. Not every cell or track must be filled:
Note that just like order
Keep in mind that with both grid-areagrid-column /grid-row ,z-index
justify-self / align-self #
justify-selfalign-selfFinally, just like flex—you can position individual grid items within their tracks using justify-selfalign-self .alignjustify-items /align-items
-
– MDNjustify-self
Just for grid. -
– MDNalign-self
Same as in flex!
You can mix and match these justify /align
The grid system is an aid, not a guarantee.
It permits a number of possible uses and each designer can look for a solution appropriate to [their] personal style.
But one must learn how to use the grid; it is an art that requires practice.