• To Grid or To Flex?
  • Michelle Barker
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Reaper622
  • Proofreader: Xionglong58, Hanxiansen

A recent Tweet by Chris Coyier got me thinking about when people usually use CSS Grid layouts or Flexbox layouts:

For those of you who already understand CSS Grid and Flexbox, what’s your favorite way to describe the difference between the two?

— Chris Coyier (@ChrisCoyier) January 25, 2019

Naturally, some of the most insightful responses came from Rachel Andrew and Jen Simmons:

Flexbox is a one-dimensional layout. One row or one column. The Grid is a two-dimensional layout. Multiple rows and columns.

— Rachel Andrew (@Rachelandrew) January 25, 2019

The Grid creates the actual columns and rows. The content will be lined up one after the other as you requested. Flexbox will not. Not only in two dimensions (the most obvious), but also in one dimension, Flexbox doesn’t fit most of the things we use it all the time today.

— Jen Simmons (@Jensimmons) January 26, 2019

However, just reading tweets doesn’t tell us the whole story. The purpose of this article is to inform the reader of the situations in which both are applicable and in which only one can be used.

When looking through the comments below the topic, I noticed that a significant number of people only use Grid for page-level layouts and use Flexbox directly in other cases. If you take this as a rule, you’re severely limiting yourself to the power of the Grid. My best advice: keep each design separate, analyze the feasibility of the alternatives, and don’t make subjective assumptions about the technology you’re using. When choosing a layout method, ask yourself these questions.

How many calculations do you have to do?

Here’s my tweet on the subject:

Grid is a better choice when it seems to me that I need calc() to do a lot of computation on the layout.

— Michelle Barker (@mbarker_84) January 26, 2019

In general, if you have to use a lot of calc() to get exact positions and dimensions (such as spacing), then it’s usually worth considering using Grid, because fr units do the heavy adaptation for you, and it saves you a lot of headaches. While this is good as a general rule, it doesn’t apply to all scenarios. These are some scenarios where you might use Grid, even if your layout doesn’t require a lot of calc(). An example is a fixed-width 2d layout where each Grid track is 200px wide – you don’t need calc() to tell you how wide the Grid track should be, but you might still want the Grid to behave. Also, flexbox will be used for some situations where you need to calculate, so this should only be used as a guide.

One or two?

One big difference between Grid and Flexbox is that Grid allows us to control the position of elements in two dimensions (multiple rows and columns), whereas Flexbox does not. Again, that doesn’t mean you can never use a Grid in a one-dimensional layout. I often use the Grid when I need to control the exact size and position of elements in one dimension. As in this example and the accompanying article:

Check out the CSS Grid component with variables and media queries written by Michelle Barker (@MichelleBarker) on CodePen

How do you want to represent elements?

A Grid is usually the right choice when you need to control the layout of a two-dimensional space. But it doesn’t mean it’s a better choice for every situation. The Grid gives you Grid tracks (multi-row and multi-column), Grid cells, and Grid regions (groups of Grid cells) and elements must be placed in these Grid cells or Grid regions. We can use Grid or Flexbox for layout, but Grid layout is much more straightforward.

Suppose we have a layout like this:

We have a grid of nine equally wide elements, arranged in three rows from top to bottom, with 20px gaps between each element:

.grid { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 200px; /* Suppose we want our rows to be a fixed height - if we want the height to change in response to the content, we can leave it as the default 'auto' */ gap: 20px; }Copy the code

The element is then placed automatically, and we don’t need to do anything else. If we really want it to be really neat, we can use Grid’s auto-fit() and minmax() methods to give us a fully responsive layout that doesn’t require media queries – try resizing this example and see what happens.

Check out Michelle Barker’s (@MichelleBarker) Grid adaptation example at CodePen.

I recommend watching Heydon Pickering’s video algorithm layout as an overview of this technique etc.

Conversely, if we wanted to create the layout using Flexbox, we might want to set the actual elements and grid container styles:

.grid {
	display: flex;
	flex-wrap: wrap;
	margin: -10px;
	width: calc(100% + 20px);
}

.item {
	width: calc((100% / 3) - 20px);
	flex: 0 0 auto;
	margin: 0 10px 20px 10px;
}
Copy the code

We need to use negative margins on the grid container to offset the fact that the total width of the inner elements may be larger than the container, so it will be wrapped to the next line. We also lose out-of-the-box responsiveness and will probably need to use media queries.

Check out Michelle Barker’s (@MichelleBarker) Flexbox layout example on CodePen.

There are several different ways to achieve the same layout using Flexbox, but they all feel a bit complicated to me – they are. We’re using flexbox for something that’s not really what it was designed to do — but that doesn’t mean it’s always the wrong choice.

Many modern CSS frameworks use some variation of this approach for this layout. As a side note, if you really want to go down this path, I heartily recommend Susy, which can handle a lot of calculations for you.

So, what’s a better choice — Grid or Flexbox? It seems that Grid has some obvious advantages, but to answer this question we need to consider what happens when we have more than 9 elements but less than 12 (the next multiple elements that allow them to fill a row). We want the new element just to go straight to the beginning of the next line as we’ve already seen, okay? Or do we want it to behave differently? Perhaps there is only one element in the next row, and we want it to take up all the available space on the row, as in example A below. Or if there are two elements, we want them to be centered, as in example B below.

With Grid layout and automatic placement, we can only choose to place the last item in the left cell, as shown in the previous example — assuming the direction value is not set to RTL (in which case elements are placed from right to left, and the last item is placed in the right cell).

Check out Michelle Barker’s (@MichelleBarker) Flexbox layout example on CodePen.

So whether you choose Grid or Flexbox for the layout above, it really comes down to the fact that you want your Grid elements to respond to changes – and to have different effects for different situations.

Would you like to replace flexbox with Grid?

When I speak, I am often asked when to use Flexbox instead of Grid, and if we still need Flexbox. As we saw in the previous example, Grid is not a replacement for Flexbox. The two can coexist very happily, and knowing when to use them can provide more power to your layout.

In the above component, we need to control the position of the text, the image, and the heading on the horizontal axis, and control how they interact with each other to some extent. The only satisfactory way to do this is with the Grid.

But I would definitely use Flexbox to build a desktop navigation menu:

Check out Michelle Barker’s (@MichelleBarker) Flexbox navigation on CodePen.

I only want to control the flow in one dimension here, and I want the elements to be responsive – which is what Flexbox does really well. Using Flexbox we can choose whether these elements are wrapped or not, and allow them to wrap gracefully if all items cannot be displayed on a single line.

How do I adapt to a browser that doesn’t support the Grid?

If we use Grid, another question we need to consider is whether the browser supports it and how we want our layout to appear on unsupported browsers (IE11 and below) :

.grid { display: flex; flex-wrap: wrap; } @supports (display: grid) {.grid {display: grid; /* Rest of Grid layout code */}}Copy the code

However, if you find yourself spending hours trying to copy the exact same layout for a browser that doesn’t support the Grid, you probably shouldn’t have Grid in the first place. The nice thing about Grid is that it can do things that flexbox can’t do alone.

We’ve discussed some very simple, common layout examples here and how to implement them using Grid and Flexbox. If you want to see some other complicated examples, check out the rest of this blog post, or stay tuned for more posts in the future.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.