CSS Grid Layout: A Cornucopia of Options

A tutorial designed to whet your appetite

CSS Grid Layout is a recent addition to the web designer’s “toolbox” that allows us to design web pages in new, interesting, and powerful ways. This article is primarily aimed toward web designers/developers who have had little to no experience with Grid Layout. Many of the articles I’ve seen on the subject tend to move on a bit too quickly into intermediate and advanced concepts. I’ll be covering why we need this new system, how to get started, and toward the end I’ll offer some advice on how (and when) we can use it safely in production.

I’ll also share some code examples and a few step-by-step instructions aimed at folks familiar with HTML and CSS. For reference here is a link to all the Codepen code examples used in this article. There are links to additional resources at the end as well.

Speaking of resources, let me save you some time and point you directly to the work of Rachel Andrews and Jen Simmons, two members of the web community who have been leading the way for Grid Layout and whose work you need to familiarize yourself with if you want to explore modern layout further.

Current layout techniques are a sad buffet

CSS Grid Layout exists because the web page layout techniques we have been using for years have serious limitations. As the web has grown and become more sophisticated, these techniques have become increasingly problematic.

At the root of the problem is the reliance on CSS floats as the cornerstone of web page layout. The underlying layout model of CSS floats is one-dimensional, which means designers wishing to use a grid system have always had to think in terms of rows. Without getting into the technical details, here’s an illustration of a simple two-column layout using the traditional technique of CSS floats. You’ll notice that even though visually there appears to be a “column” below figure B, we accomplish this through what is essentially a hack, i.e., there are no true columns available for use in our current system.

A.) Header B.) Image C.) Main Content

By contrast, the CSS Grid Layout system that we’ll be exploring has a mental model that looks like this:

Here we have two-dimensions, not only do we have rows (in this case two of them) but also columns (also two). This is a huge deal and the biggest conceptual difference that designers and developers will need to adjust to. If this doesn’t make sense immediately, don’t worry — the rest of the article will clear things up, I hope.

Here’s another way to put this into perspective. Currently, for a web designer or developer, only having CSS floats to work with is like walking into a buffet where soup and salad are your only options. Technically a meal, but...meh.

CSS Grid Layout, on the other hand, is a veritable smorgasbord. Options, choices, sweet delights! You will be tempted to dive in and sample everything, I promise you.

To be fair, CSS floats have received help as technology has improved, most notably with the recent introduction of CSS Flexbox (which I’m largely going to stay away from in this article.) Suffice to say, Grid Layout and Flexbox work well together, and there are already many good resources online covering these techniques.

In terms of grid systems, over the years we have also seen the emergence of frameworks such as Bootstrap and Foundation, both of which have very clever ways of giving designers/developers access to “grid layout” templates. To be clear though, these systems simply tuck the usual float techniques into “behind-the-scenes” code. CSS Grid Layout is something completely different, and it’s perhaps one of the most exciting developments on the web in recent years.

Before we dive in, I want to set some expectations. There is *a lot* to cover in the Grid Layout spec. If we look at the number of new CSS properties we have access to, that number is seventeen. Seventeen. New. Properties. Let that sink in for a second. In this article I will only cover six or seven of those properties, thereby leaving a lot untouched. My goal is to let you savor and explore the main dishes of Grid Layout for a while, and then you’re on your own to explore and indulge your appetite.

There’s one more thing I’d like to emphasize. Having a basic understanding of HTML and CSS is useful in order to follow along with the rest of the article, but it’s also important to clear your mind and accept this model as brand new without trying too hard to make comparisons to the past. I have a friend who might be able to help you with that.

There, that’s better.Now let’s join the buffet line!


Setting the table

The idea of a grid system has been around for a very long time. Think of how hard it would be to print newspapers on a daily basis without guidelines on how to format content and create a hierarchy to distinguish the most important articles from the less important ones.

An 8 column grid from an important day in US history.

CSS Grid Layout will allow you to create similar combinations of rows and columns, but let’s begin with the basics. Below is a diagram of a grid with 3 rows and 6 columns. Here’s your first pop quiz! Grid Layout has a component called the grid line, how many grid lines do you think the grid below has?

Because a grid line is created on both sides of a row or a column, the answer is that there are 7 column grid lines and 4 row grid lines (I’ve labeled them below). Additionally, the space between two adjacent grid lines is referred to as a grid track. Our grid has multiple grid tracks that I could have illustrated, but I randomly highlighted the 5th column (seen in orange) here. In addition to grid lines and grid tracks, we also have the grid cell which is the intersection of any given row or column — think of it as the smallest single unit within the grid. I highlighted a single cell (seen in green) within the 2nd column and 3rd row.

Building this layout is fairly straightforward; I’m going to leave out the HTML structure as well as the background and border styles, and just focus on the grid CSS. Here’s the basic code:

.grid {
display: grid;
grid-template-columns: 150px 150px 150px 150px 150px 150px;
grid-template-rows: 150px 150px 150px;
}

So we first instruct the container we’re styling to be displayed as a grid, which gives it all the “superpowers” that will soon follow. Next, we define each column to be 150px wide and specify six of them. Similarly, we specify 3 rows, each with a height of 15opx.

I’ve placed the code for this layout here in a Codepen, and I invite you to go in and change the values to see how it works. I used the long version of the code for easier understanding, but we can actually use the repeat syntax to say “repeat this row or column X number of times,” which is more elegant and efficient:

.grid {
display: grid;
grid-template-columns: repeat(6, 150px);
grid-template-rows: repeat(3, 150px);
}

Right now there’s no space between our rows and columns, but let’s add some. To do this, we turn to grid-gap. You can use any number of values to specify the gap, I’m using pixels, but you could use other values as well (ems, rems, etc.)

.grid {
display: grid;
grid-template-columns: repeat(6, 150px);
grid-template-rows: repeat(3, 150px);
grid-gap: 30px;
}

Which gives us this:

(As a side note I just recreated a famous optical illusion, where your brain tries to “see” light gray dots between the gutters, but if you look at one directly it disappears!).

The code for this example can be found here. Take a look and play around, you can also experiment with setting either the column gap or row gap independently, to do that, you would use the following syntax:
grid-gap: 15px 100px; here the first value (15px) is the row gap and the second value (100px) is the column gap.

So we’ve just gotten started, but think of how useful this already is! Creating a reliable image gallery, for example, is still really annoying with our current tools, but with Grid Layout it becomes almost trivial to build one on the fly. Here’s an example I quickly mocked up. Feel free to dive in and play around with the rows, columns, gap, and the size of the cells.


A taste of something new

Working with real content is where things get interesting; in 2012, I had the unique opportunity to work with an early version of Grid Layout for a project I was doing with Microsoft (which you might be surprised to learn was primarily responsible for writing the original specification). If you’re interested in learning the backstory, hit me up on Twitter or in the comments, but the short version is that for about a month I helped build a Windows 8 app and was encouraged to use Grid Layout (and Flexbox) because of the full support on that platform.

I remember for the first few days being totally confused and over-engineering everything, I kept trying to apply my old school CSS skills to this new model and getting in my own way. Finally something clicked, the clouds parted, and I yelled, “I see the light! I SEE IT!”

Gratuitous link that represents my elation after learning Grid Layout basics

This caused my co-workers a bit of alarm, but once I showed them why, they chilled out and went back to playing Bad Piggies, the underappreciated sequel to Angry Birds.

So here’s a version of what I showed them. We start with a single <div> element that has been given a background color and border so we can visually understand what is happening; then we throw some text in there. Let’s try the first amendment to the US Constitution. Here is the HTML for the following example:

<div class="grid">
<div class="grid-item">
<h1>The Bill of Rights</h1>
<h2>Amendment I</h2>
<p>Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances.</p>
</div>
</div>

If you want to play along, here is the starting code. This is the only CSS used: a basic background color and border on the .grid-item class selector to help you understand the behavior of the div within our rows and columns.

.grid-item {
background-color: #d8d8d8;
border: thin black solid;
}

As you might expect, the div expands to the edge of the browser, the default behavior.

Now let’s bring in some new firepower named the fr unit which is the standard fluid unit of measure for Grid Layout. It’s similar to percentages, but best defined as representing a fraction of the available space in the grid container (fraction = fr , see how they did that?). To see it in action we’re going to create a four column layout, and each column will have a value of 1fr. The following animation demonstrates this behavior.

With 1fr the width of the div is a single column taking up all the available space, so there is no change. Adding another 1fr creates another column and makes the width of our div take up exactly half of the available space. Adding yet another 1fr unit creates a third column and makes the width of our div take up one third the available space. Finally, adding the last 1fr unit creates a four column layout and our div takes up a quarter or 25 percent of the available space.

Here’s our code, simple as can be:

.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
}

But we’re just getting started, because having 1 fractional unit implies that we can increase that value, (which we can!) so let’s make the first column 2fr wide.

.grid {
display: grid;
grid-template-columns: 2fr 1fr 1fr 1fr;
}

This has the visual effect of increasing the width of our div. Just to be clear, we still have four columns, we’ve simply defined 5fr units and two of them are reserved for the first column, which means it occupies ⅖ of the available screen space (or 40% if you like thinking that way.) The first screenshot here has all four columns set to 1fr, the second screenshot has the first column set to 2fr and the remaining three columns at 1fr.

grid-template-columns: 1fr 1fr 1fr 1fr;
grid-template-columns: 2fr 1fr 1fr 1fr;

A small palate cleanser

So you still might be struggling with visualizing this; I know I was originally, so allow me to help. One of the challenges of Grid Layout is that your grid tracks and lines are invisible by default. The classic CSS technique of turning on borders doesn’t work here, and Grid Layout doesn’t support border styling in this way. At the time of writing this, one of the best methods to visualize your grid overlay is with Firefox’s Developer Edition browser. Using the Inspector (located within the Developer Tools) you can toggle the grid overlay in order to see your layout structure.

I have no doubt that other browsers will follow suit with a similar feature, and I hope they do, because having that visual indicator is invaluable. Meanwhile, you should download the Developer Edition if you’re serious about learning Grid Layout. Triggering the grid overlay is a matter of locating the declaration display: grid using the Inspector and then clicking the “waffle” icon as seen in this animation.

Again, this isn’t required to follow along with this tutorial — merely a helpful tip for later. Let’s continue our exploration of the fr unit by looking at rows. Let’s add the following code to our styles:

.grid {
display: grid;
grid-template-columns: 2fr 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
}

Following the previous logic of what we did with grid columns, can you guess what this will do?

If you said “split the available horizontal space into two equal areas,” then you are correct. However our div container has not been affected, it’s still sitting in the first row.

Now for our next trick: we have a single div and a grid layout with four columns and two rows (all using fr units), so let’s have some fun and start moving our div around the grid. Note that we are now declaring this rule in the class selector .grid-item, so let’s put it on the second row.

.grid-item {
background: #D8D8D8;
border: thin black solid;
grid-row: 2;
}

Which gives us this:

What if we wanted to move our div to the second column on the second row? Sure!

.grid-item {
background: #d8d8d8;
border: thin black solid;
grid-row: 2;
grid-column: 2;
}

Let’s just pause here for a moment because in the education business this is what we call the “teachable moment.” You’re witnessing layout behavior here that is completely different from our existing models of floats and even Flexbox. For many people new to CSS Grid Layout this is the “Aha!” moment:

Grid Layout represents an independent system of rows and columns, and we can position (and reposition) our content within it easily!

To further clarify, our div has a shorter width because it is placed in the second column which is 1fr. This is a feature, not a bug. If we want our div to span columns two and three, we have to instruct it to do so.

.grid-item {
background: #d8d8d8;
border: thin black solid;
grid-row: 2;
grid-column: 2 / span 2;
}

In the previous screenshots I have Firefox’s grid overlay turned on, but as a reality check we should look at this in the browser without the overlay.

As a “layout” in the browser it’s pretty uninspiring I admit, but as an exercise in understanding Grid Layout, it raises some important questions. For example, our div is collapsing and expanding based on the width of the browser; how could we prevent that if we wanted to? One solution lies in the units we’re using for our columns. Remember that we are exclusively using fr units, which are designed to adapt to the available space, but we’re allowed to mix and match fluid and fixed units (of measure). Let’s set the width of columns 2 and 3 to be 150px each:

.grid {
display: grid;
grid-template-columns: 2fr 150px 150px 1fr;
grid-template-rows: 1fr 1fr;
}

Once we’ve done that, let’s see what happens in the browser now. I’m going also to turn the grid overlay back on to make the fluid and fixed column behavior more obvious.

As you can see, the width of our div stays fixed at 300 pixels and the two columns on either side adapt based on the available space. This ability to define a “fixed” width for specific columns (or rows) is incredibly useful for certain scenarios. For example, imagine you’re building a responsive video player with a number of button controls (play, stop, skip, etc.). You could set the tracks where the controls are located to be fixed units and thereby force them to stay the same size, while the rest of the player could still be completely flexible.

If you look back at the previous animation, note that because there is no content in columns one or four, when the browser window reaches its narrowest point, these empty columns collapse to zero and our content is centered.

Its easy to adjust and experiment with your Grid Layouts. For example, to place our content div back into the first row and center it horizontally requires two small tweaks. The first change is to the parent grid container stating that the fourth column should be 2fr wide instead of 1fr.

.grid {
display: grid;
grid-template-columns: 2fr 150px 150px 2fr;
grid-template-rows: 1fr 1fr;
}

The second change is to move the div from row two back to row one:

.grid-item {
grid-row: 1;
grid-column: 2 / span 2;
}

If we also remove the background color and border, the final result is underwhelming, I know. However, it’s not the final layout that is the star of the show; it’s how we got here.

You can check out and tinker with the final code here. In the next section, I’ll walk through a more complex “real world” layout.


Digging into the main course

In this section is a working demo of a page that uses three different Grid Layouts, each contained within a different media query. The project I have in mind is a short snippet of content pulled from Wikipedia describing the classic jazz album, “Ella Fitzgerald Sings the Duke Ellington Song Book.” The material I’ll be working with is minimal, consisting of a heading, a few paragraphs, and three photos. To give you sense of what I’ll be working toward, here is the final version of the project (with a responsive layout and all that jazz).

There will be a few new concepts thrown in, the most notable being grid area. With grid areas we can use plain English to describe sections of our Grid Layout. With that in mind, we will start by defining some grid areas in a layout designed for “mobile-first.” Here is my HTML:

<div class=”container”>
<div class=”albumtitle”></div>
<img class=”duke”>
<img class=”ella”>
<div class=”album-desc”></div>
<img class=”bandphoto”>
<div class=”credits”></div>
</div>

I left out the content and image src information here for space reasons, but I want to point out something very important. The items with the class selectors duke, ella, and bandphoto are attached to <img> elements. What this tells us is that grid items can be any element and this goes a long way toward simplifying our markup. Again, if you’ve been a web developer for any period of time, this structure might feel too elementary, but it’s another example of how we need to “unlearn” old habits based on our traditional way of doing things (in this case, we might feel tempted to nest those images within another <div> element, but it’s not necessary).

In terms of the CSS for our Grid Layout, we’ll specify a new container as a grid with grid-gap and padding; nothing new here so far.

.container {
display: grid;
grid-gap: 1em;
padding: 1em;
}

Now for the new stuff — on the left is my desired layout, and on the right is the naming convention I will use:

The code looks like this:

.container {
display: grid;
grid-gap: 1em;
padding: 1em;
grid-template-areas: “head head”
“photo-1 photo-2”
“main main”
“spread spread”
“footer footer”;

}

Here is your first lesson when defining grid areas — your syntax must match the number of columns (and rows) for your desired layout. In this case, we need a two-column layout to support the two side-by-side images in the second row. Next, for each class we declare the grid-area property and then the value of the relevant grid area we want associated:

.albumtitle {
grid-area: head;
}
.duke {
grid-area: photo-1;
}
.ella {
grid-area: photo-2;
}
.album-desc {
grid-area: main;
}
.bandphoto {
grid-area: spread;
}
.credits {
grid-area:footer;
}

Here’s the code for this— take a good, hard look at what’s happening in the browser as well as the code.

Previously we saw how you could position a div to a specific row or column using the grid-template syntax, and you could also force that div to span using the span syntax. This is essentially the same thing; the key difference here is that we are using grid areas that have logical content-based names, thereby creating a better mental model of your grid structure. It may be easier for you to work like this moving forward, and it will definitely be easier for other people looking at your code to understand.

If you’re a web designer/developer reading this, I hope you’re getting excited about the potential of this new model. If you need a bit more persuasion or evidence, in the next section I’ll add some more flavor to our meal with the addition of classic responsive design techniques.


Pigging out with media queries

Our existing layout is simple and works well on small screens, but as we expand the browser window, we can see that the layout is in need of some help.

As I mentioned earlier, there’s a lot going on in the Grid Layout spec, there’s actually an auto-placement algorithm and a few other tricks that allow you to place content on screen based on the available empty space, but that’s for another time and place. For now, I’d like to keep exploring the basics of using grid areas to define your layout. To do this, we’re going to turn to our old friend media queries for some help, and when our viewport hits a certain width, we’re going to display a more complex layout.

This is where it gets really fun; we’re going to add a media query at 34em (equivalent to 550px) and then do two things:

  1. Add another column using our grid-area property.
  2. Reposition our two photos by placing them into the first column.
@media (min-width: 34em) {
.container {
grid-template-areas: “head head head”
“photo-1 main main”
“photo-2 spread spread”
“footer footer footer”;
}
}

The first screenshot below shows the layout as seen normally in the browser. In the second screenshot I’ve turned on the grid overlay in Firefox to help you see and understand the structure.

Pretty cool! Again, note that our CSS grid-template-area syntax is mapped to the page layout structure, helping you visualize your rows and columns.

Let’s keep digging in and add a third media query with a completely different layout.

@media (min-width: 72em) {
.container {
grid-template-areas: “. . head”
“photo-1 photo-2 main”
“. . spread”
“footer footer footer”;
}

The syntax for row 1 (“. . head”) and row 3 (“. . spread”) is new for us. You can think of the “.” syntax in grid-template-area as a placeholder; in other words, we’re choosing not to explicitly label those areas. So here we’re saying:

  1. In the first row, the “head” area starts at column three.
  2. In the second row the “photo-1” area starts in column 1, the “photo-2” area starts in column 2, and the “main” area starts in column 3.
  3. In the third row, we start the “spread” area in column 3.
  4. In the last row, we specify the "footer" area across the entire grid.

Here’s the resulting layout. Again, the first screenshot shows the image as normally seen in the browser, and the second shows the grid overlay in Firefox.

The Duke and Ella photos might feel overpowering compared to the other content. So what if we wanted to make them smaller? You’ve already seen the tools needed for this. Can you guess what they are?

The answer is the grid-template-columns property, which we looked at earlier. We can define the width of the first two columns using any of the units of measurement at our disposal. In my example, I’ve decided to use the vw unit mostly because I can. The syntax vw stands for “viewport width,” and it has a companion named the vh unit which stands for “viewport height.” If you haven’t used these units before, they allow sizing of elements to be relative to the size of the viewport. Here’s a good introduction to them (useful but not required to continue).

@media (min-width: 72em) {
.container {
grid-template-areas: “. . head”
“photo-1 photo-2 main”
“. . spread”
“footer footer footer”;

grid-template-columns: 18vw 18vw 1fr;

}

So here, the width of column one and two are each set to 18vw making the width of the combined columns 36vw, which is roughly ⅓ of the browser window and gives us this in our final layout.

If you’d like to examine this project as is, the code is here.

One of the things I would like to emphasize is that the grid-area syntax makes it quick and easy to explore different variants of layout. For example, Eric, a reviewer of this article made a few quick changes to the syntax and created something a little different:

grid-template-areas:
“. . head”
“photo-1 photo-2 main”
“photo-1 photo-2 spread”
“footer footer footer”;

This change probably took him a grand total of 5 seconds in the code and the result is a layout that emphasizes the band photo and makes everything a bit less “grid-like” than my example.

The overall point is that this type of layout change would have taken much longer with our old model. Actually, to take it even further, I would argue that the technical hurdles we faced all these years often discouraged us from this type of experimentation. CSS Grid Layout has the potential to unlock our creativity by giving us the ability to control the placement of our content using very simple syntax.

A bit of dessert

Limiting my demonstrations in this tutorial has been difficult, namely because there’s so much more to explore. I hope you have room for one more new concept. It’s a small but important feature of working with grids and has to do with alignment of individual items within your rows and columns.

To illustrate my point, let’s look at our second layout, and specifically what’s happening in the third row with the alignment of the Ella photo and the band photo.

The images of Ella and the band are always aligned to the top of the row, and this is fine at the most narrow width(s), but as the browser gets wider and the Ella photo begins to scale, the bottom edges of the two photos are no longer aligned and this creates a gap that some might find annoying.

So, as with most things involving web design, there are a few different ways we could address this. The one I’ll focus on is the property align-self which is a feature in Grid Layout that allows you control the way items are aligned within a grid row. Let’s look at a snapshot of this layout with the grid overlay turned on.

The first thing we need to do is create a new class selector for the item we want to control, which in this case is the band photo. Then we’ll add the align-self property with the value of start.

@media (min-width: 36em) {
.container {
grid-template-areas: “head head head”
“photo-1 main main”
“photo-2 spread spread”
“footer footer footer”;
}

.bandphoto {
align-self: start;
}

}

And this does…absolutely nothing. The reason being that start is actually the default value for items within a row — they always start at the top. Let’s change the value to end. (I’m going to leave out the other styles for space reasons).

.bandphoto {
align-self: end;
}

Aha! This aligns the band photo to the end of the row. The first screenshot shows this with the grid overlay on; the second one shows this with the grid overlay off.

There are only three values you can use for the align-self property. Let’s try the last one, which is center.

.bandphoto {
align-self: center;
}

This is the result:

You can see the final result here. This is probably the choice I would make as it gives us equal amounts of space above and below the band photo at all times. It’s fantastic that we have this level of control. In a similar fashion, if you want to control the alignment of items within a column, there is also the property justify-self available (although I won’t be exploring that here). This feature of Grid Layout raises an interesting question: by having access to what is essentially an override, are we defeating the purpose of the system? In other words, if one of the benefits of Grid Layout is to make objects line up easily and automatically, doesn’t this “break” that?

I would argue no, it doesn’t; in fact, this feature gives designers great power in creating complex and sophisticated layouts, but it needs to be used wisely and with intent. In the book, Making and Breaking the Grid, Timothy Samara discusses the struggle many print designers have had with grid systems over the years. He states that while some designers feel they can bring “precision, order, and clarity” to the design process, others fear they are “symbolic of Old Guard aesthetic oppression, a stifling cage that hinders the search for expression.” Regardless of where one stands, the real winners are all of us in the web community. Now we can actually have this debate with a legitimate grid system at our fingertips.

Here is the final code again, including the center-aligned band photo. Please explore, fork, and modify as you wish. If you want some guidance as to where to start, here are some things to try:

  • Increase/decrease the media query values and see the effect it has as you change the browser width. Try adding a fourth media query for even larger screens (assuming you have a monitor capable of displaying it).
  • Keep your browser at one size and experiment with changing values such as the grid-gap as well the column sizes and layouts
  • Instead of the vw units I used in the final example, try ems, px and fr units to size the columns. Do the same thing for the rows.
  • Add some background-color properties to the various class styles and see what effect it has.

That’s it for our main project. We still need a reality check to discuss how and when we can realistically begin using CSS Grid Layout though.

Here comes the bill . . .

We’ve had our small, yet satisfying feast, and believe me when I tell you that there’s a lot left on the buffet table that we haven’t even touched. Let’s cut to the chase — what’s the cost of all this grid goodness? We’ve already hinted at the fact that Grid Layout is extremely new and that older browsers will display your content but with none of the layout. So what exactly is the status in browsers anyway?

Our go-to resource for these questions is the invaluable caniuse.com which constantly updates browser support for all the things. At the time of this writing, they state CSS Grid Layout support is at 62.4 percent global support; be sure to check this page for the most recent numbers because this changes frequently. Specifically, we have browser support in the most recent desktop versions of Google Chrome, Firefox, Safari, and Opera. Microsoft’s IE 11 and Edge offer partial support, and the future roadmap for those browsers includes full support. If that 62.4 percent support number is bumming you out, stay with me for just a few more paragraphs, where I’ll present the solution that makes this more palatable — I promise.

On the mobile side, the most recent versions of Safari for iOS and Chrome for Android support Grid Layout, although if you go back a few versions, you’re going to have problems. So we need to look at the road-map for browser support a bit closer — otherwise all of this was just an interesting technical exercise and not something you could use anytime soon.

Browser Support

Although caniuse.com is a fantastic resource, its support numbers only tell part of the story. Rachel Andrew recently posted this encouraging tweet:

The context here is user visitor data from a single website that Rachel has access to, and 83 percent is an encouraging number. The caveat is that this is data from a tech site, so the average visitor is more likely to have an up-to-date browser. But the key point is the rate of growth; 0–83 percent support in two months is unheard of and very inspiring news.

In the “old days,” browser technology was updated on a much slower timeline and required users to manually download and install the software. Today, not only do browser updates come more frequently, but they tend to auto-update as well. Most users get fresh versions of the most recent browser behind-the-scenes, and manual updates are becoming more of the exception — not the rule. Based on this trajectory, it’s possible that we’ll have close to 100 percent support for Grid Layout across all modern browsers by the end of 2017 (please do not quote me on that).

Fallbacks

While browser support for Grid Layout is encouraging, it’s obviously only part of the picture. We still have all of those older browsers out there in the wild, and they will never support Grid Layout. So these days we naturally turn toward fallbacks. Fallbacks are a common part of today’s web development landscape, and web developers have become quite accustomed to using them. I’m not going to go deep into code at this point. Instead I will get straight to the primary solution I hinted at earlier which is CSS Feature Queries.

A CSS Feature Query is a way to test a user’s browser for support of any given CSS property. The basic code of a feature query looks like this:

@supports (display: grid) {
.container {
/* add rules for grid supporting browsers here. */
}
}

If this syntax looks familiar to you, it should. Feature queries are very similar to media queries. Let’s say you have an existing site that uses floats and want to enhance it with Grid Layout. You would start with a feature query, similar to the one above, and then add your CSS grid code. Additionally, you would need to add rules that remove anything required for the older layout.

That’s the basic idea. The great news is that because feature queries are supported in all the browsers that support Grid Layout, you can use it exclusively to provide dual support. How to do this is a topic for another day, but there are a number of excellent resources I can point you to — the first is this article by Jen Simmons, which is a good introduction to the subject of feature queries, and then this more grid-specific tutorial, CSS Grid Layout and Progressive Enhancement.

Worthwhile examples of Grid Layout in the wild

An obvious question that comes up is what sites are using Grid Layout “for real” today — i.e., in a production website, not just as a technical demo? The examples are few and far between as I write this, but there are a few sites I can recommend.

  • Grid by Design is your one-stop-shop for all things grid. The aforementioned Rachel Andrew created this site to share examples, tutorials, and resources, and the site itself uses Grid Layout. Required reading!
  • The website for Patterns Day, a web conference, uses Grid Layout to a degree. Jeremy Keith, designer of the site, documented this process on his blog as well, and there are some good takeways to be found there.
  • Eric Meyer’s personal website meyerweb.com uses Grid Layout, and just as importantly, he documented his process with an article, “Practical CSS Grid: Adding Grid to an Existing Design” over at A List Apart.

Additional resources

  • The grid specification is the official source of truth for laying out the rules and syntax for Grid Layout and should be your first stop when you need definitive answers. Over the years these specifications have become a little easier to read, but a lot of people still have trouble sorting through all of the syntax and examples. Luckily for us, Rachel Andrew has a blog series that can help you interpret the specification; here’s Part One, if you’re interested.
  • Speaking of Rachel Andrew, her work is the gold standard for all things grid, and she has created so much content including articles and tutorials that you could spend quite a bit of time with that material before ever looking elsewhere.
  • However, having multiple resources is always a good thing, so be sure to explore the material that Jen Simmons has created, which includes Grid Layout theory and techniques. In addition to her fantastic lab demos, there is also her Learn CSS Grid page which will do a better job than this section of staying up-to-date — so just go there.
  • If you don’t subscribe to the email newsletter, Responsive Design Weekly, you’re missing out on a lot of important news, so get on that. For example, Edition #256 lists a number of resources on both Grid Layout and Flexbox and has lots of links to excellent articles, interactive demos, and more.
  • For comparison, in the old days of CSS layout there was a 3-column liquid layout referred to as the “holy grail,” due to its elusive qualities. This was such a headache that in 2006, it required a 2,000 word article to explain all of its intricacies. Here is the holy grail layout reproduced in about 35 lines of CSS. Go ahead and check it out for yourself.

Last, but hopefully not least, here are all my code examples on Codepen from this article: