Blog

CSS Grid vs. Flexbox: Which Ought to You Use and When?

Flexbox and CSS Grid are two CSS format modules which have develop into mainstream lately. When to make use of which, is one other query nonetheless.

Each permit us to create advanced layouts that had been beforehand solely attainable by making use of CSS hacks and/or JavaScript. Flexbox and CSS Grid share a number of similarities and plenty of layouts will be solved with each. Let’s see if we will make clear when you must use Flexbox and when you must use CSS Grid.

Business Recap

The CSS Grid vs. flexbox debate is presently the most well liked subject within the CSS neighborhood. In the event you comply with trade information you should have seen many nice articles seem these days, equivalent to:

  • Rachel Andrew blogged on the query already again in 2016 and later continued discussing it in additional element.
  • Final month, Chris Coyier began a viral Twitter thread that ended up in an extended article with some cool code examples on CSS-Methods.
  • Michelle Barker additionally responded to Chris’ Twitter thread by authoring one other glorious Grid vs flexbox article in her in style CSS {In Actual Life} weblog.
  • The MDN Neighborhood has created some thorough docs on the fundamental variations between Grid and flexbox, which is presently one of the best obtainable documentation on the topic.
  • An article by Geoff Graham discusses how the developments in CSS, together with Flexbox and Grid, have influenced fashionable CSS writing practices. It sheds mild on the options which have had essentially the most affect on present CSS approaches, providing insights into the continued evolution of CSS design and coding.

You can even discover many different associated weblog posts, articles, movies, and discussions all around the internet. As the subject is more likely to keep related sooner or later, I’d advocate studying a number of the articles above and growing your stance on the query, as nothing is ready in stone but.

Right here’s one other take.

One vs. Two Dimensions

An important factor to know while you be taught flexbox is that it is one-dimensional, whereas CSS Grid is two-dimensional. Flexbox lays out objects alongside both the horizontal or the vertical axis, so you need to resolve whether or not you desire a row-based or a column-based format.

The cross axis is always perpendicular to the main axis The cross axis is always perpendicular to the main axis
The flexbox cross axis is at all times perpendicular to the primary axis. 

A flex format may also wrap in a number of rows or columns and flexbox treats every row or column as a separate entity, primarily based on its content material and the obtainable house.

Alternatively, CSS Grid enables you to work alongside two axes: horizontally and vertically. Grid means that you can create two-dimensional layouts the place you possibly can exactly place grid objects into cells outlined by rows and columns.

That is how W3C desires us to make use of flexbox and Grid, nonetheless, observe often overrides principle, and never everyone seems to be a fan of the one-dimensional vs. two-dimensional narrative. As an example, Chris Coyier made the next assertion in his aforementioned article:

“I am not the world’s largest fan of the “1D” vs. “2D” differentiation of grid vs. flexbox, solely as a result of I discover most of my day-to-day utilization of grid is “1D” and it is nice for that. I would not need somebody to suppose they’ve to make use of flexbox and never grid as a result of grid is just while you want 2D. It’s a sturdy distinction although that 2D format is feasible with grid although in methods it isn’t in flexbox.”

And, that is how CSS works in actual life. We are able to create two-dimensional layouts with flexbox (on account of its wrapping capability) and one-dimensional layouts with CSS Grid (on account of its auto-placement capability), too.

Though flexbox is initially not for constructing grids, it’s often used that method. One of the best instance is Bootstrap 4’s grid system which is predicated on flexbox. All Bootstrap 4 websites on the market makes use of flexbox to perform two-dimensional layouts, consisting of rows and columns. And, there are different in style instruments equivalent to Flexbox Grid that do the identical.

When to Use Flexbox vs Grid

The commonest false impression concerning the two format modules is that Grid is for full-page layouts and flexbox is for smaller parts. This isn’t the case in any respect. All of the authors talked about above warn towards this strategy, as it may severely restrict prospects. You have to assess every format individually on a case-by-case foundation to choose the higher choice.

Concentrate on Content material Placement: CSS Grid

CSS Grid focuses on exact content material placement. Every merchandise is a grid cell, lined up alongside each a horizontal and a vertical axis. If you wish to precisely management the place of things inside a format, CSS Grid is the way in which to go. The W3 docs of the Grid module assert:

“It supplies a mechanism for authors to divide obtainable house for format into columns and rows utilizing a set of predictable sizing behaviors. Authors can then exactly place and measurement the constructing block parts of their utility into the grid areas outlined by the intersections of those columns and rows.”

With flexbox, it’s exhausting to foretell habits at sure viewports and you may get stunning outcomes. In fact, you possibly can set the widths and heights of flex objects or make use of the calc() perform however you then lose flexbox’s fundamental attraction: flexibility.

This isn’t the case with CSS Grid. It has properties equivalent to grid-template-rows and grid-template-columns and utilities just like the fraction unit that allow you to exactly calculate every thing. Therefore, Grid is very appropriate for creating uncommon layouts like damaged, asymmetrical, and overlapping layouts.

CSS Grid additionally makes it attainable to create responsive layouts with out utilizing media queries. The concept comes from Heydon Pickering who just lately revealed a YouTube video about algorithmic layouts. He introduces a easy Grid method that makes grid cells wrap and adapt to any viewport sizes:

1.container {
2 show: grid;
3 grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
4 grid-gap: 1rem;
5}

Though the format wraps primarily based on the obtainable house, it’s nonetheless not content-aware like flexbox, because the content material contained in the objects doesn’t flexibly stretch out:

Concentrate on Content material Move: Flexbox

Flexbox focuses on content material circulation somewhat than content material placement. Widths (or heights) of flex objects are decided by the content material of the merchandise. Flex objects develop and shrink in accordance with their internal content material and the obtainable house. That is how W3C’s flexbox docs clarify the targets of the format module:

“… (flexbox) positive aspects easy and highly effective instruments for distributing house and aligning content material in ways in which internet apps and complicated internet pages usually want.”

Briefly, flexbox lets you allocate house and align objects flexibly. Let’s see how Heydon’s grid would appear like with flexbox. The next code provides a margin of 0.5rem to every flex merchandise (as flexbox doesn’t have a spot property, we have to use the damaging margin hack).

1.container {
2 show: flex;
3 flex-wrap: wrap;
4 margin: -0.5rem;
5}
6.merchandise {
7 margin: 0.5rem;
8}

As you possibly can see under, the primary flex merchandise with the lengthy content material stretches out so far as wanted:

In fact, you can also make fix-width flex objects utilizing the width or flex-basis properties. Nonetheless, when you achieve this you lose flexbox’s content-awareness which is the primary purpose for its existence. You can even see above that flexbox treats every row independently. Completely different rows align flex objects in a different way, primarily based on the quantity of textual content inside them. There aren’t any columns right here and this isn’t a grid however a one-dimensional format.

Flexbox additionally means that you can resolve how your content material ought to behave when there’s an excessive amount of house or not sufficient house on the display. I wrote concerning the subject intimately in my article about flexbox sizing. Utilizing the flex-grow and flex-shrink properties, you possibly can obtain a very fluid format that optimizes the allocation of flex objects at each viewport measurement.

There are different typical use instances of flexbox as effectively, equivalent to centering objects, adjusting the final merchandise(s) of lists, sticking the footer to the underside of the web page, and creating responsive menus. You’ll find much more flexbox utilization examples within the MDN docs.

Browser Assist for Flexbox vs CSS Grid

Flexbox has good browser help, whereas CSS Grid will not be supported by IE11- and Edge 15-. 

CSS Flexible Box Layout Module (as of time of writing)CSS Flexible Box Layout Module (as of time of writing)CSS Flexible Box Layout Module (as of time of writing)
CSS Versatile Field Structure Module (as of time of writing)

CSS Grid Layout (as of time of writing)CSS Grid Layout (as of time of writing)CSS Grid Layout (as of time of writing)
CSS Grid Structure (as of time of writing)

Articles often advocate utilizing flexbox as a fallback for CSS Grid, nonetheless many builders take into account it an excessive amount of trouble and would somewhat create their layouts solely with flexbox.

However flexbox isn’t good, both. It has a few points being collected within the Flexbugs repo on GitHub (with cross-browser workarounds for the bugs). In the event you stumble upon a problem whereas working with flexbox it’s price taking a look at this listing, as you would possibly discover the answer to your drawback.