Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
CSS Layout – Grid vs. Flexbox (codecoda.com)
96 points by xxlcloudinc on Oct 13, 2020 | hide | past | favorite | 66 comments


It's extremely disappointing that, other than Firefox, browsers have refused to implement subgrid[1]. As I understand it, this feature was deferred from the basic grid spec with the understanding that it was still necessary and would be implemented, not so it could consequently be ignored. If Mozilla was capable of implementing subgrid, Apple and Google certainly have the capacity to do so.

[1] https://caniuse.com/?search=subgrid


> It's extremely disappointing that, other than Firefox, browsers have refused to implement subgrid

The way I understand the situation in Chromium is that they are slowly moving to a new layout system called LayoutNG [0]. The current grid implementation is in the old layout system however and they don't want to spend time extending it just to abandon it a few months later. There's already an ongoing work to support grid (GridNG) in LayoutNG [1] and once that's done, adding support for subgrid should be "fairly straight forward" [2].

[0] https://bugs.chromium.org/p/chromium/issues/detail?id=591099

[1] https://bugs.chromium.org/p/chromium/issues/detail?id=104559...

[2] https://bugs.chromium.org/p/chromium/issues/detail?id=618969...


I've worked around this limitation using `display: contents`. It's not the same, but it's worked in a pinch


One of the best places to learn about these is on css-tricks:

- A Complete Guide to Flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

- A Complete Guide to Grid: https://css-tricks.com/snippets/css/complete-guide-grid/


I usually prefer text to video tutorials, but for me one of the best introductions to Grid was this video from Mozilla:

https://www.youtube.com/watch?v=KOvGeFUHAC0

Seeing it like that really made me appreciate how much boilerplate Grid could let you cut back on.


Also "Flexbox Froggy"


And its grid counterpart Grid Garden. https://cssgridgarden.com


Yeah. That’s much nicer than the references; gives you a nice intuition for it.


My rule of thumb:

2d -> grid

1d -> flex

For the resources, I recommend:

Flexbox: https://flexboxfroggy.com/

Grid: https://cssgridgarden.com/


Agree.

Grid is great for 2D layouts especially if you're going to shift stuff around (e.g. responsive versions of the layout).

With Flexbox, you can sorta do it but it always feels way too hard, even if your layout is convenient enough to be able to use the order rule.


> Grid is great for 2D layouts especially if you're going to shift stuff around (e.g. responsive versions of the layout).

Exactly!


My rule: grid by default

  body,
  nav,
  header,
  article,
  section,
  figure,
  form,
  div,
  header,
  footer,
  button,
  .button {
    display: grid;
  }
.button is gross but included as older Chrome/Edgium have issues using grid/flex on proper buttons.


nav, figure and button: why wouldn't flex cut it?


because they nearly always might have two dimensions.

Good question. Think of a price button (to choose yearly payment, instead of monthly).

----

$299/year upfront *

Less than $25 a month

cancel anytime

----

* The symbol would be smaller, the number bigger, lined up in a horizontal row.


I would use: `flex-direction: row`. And use wrap the number and asterisk in a `span` and style them as needed.


That's a very common rule of thumb.

Where I struggle is that grid can do most of what flexbox does in 1d but ... generally simpler if you're relying on breakpoints to change your layout.


There are some things that grids aren't optimized for, one example that comes to mind is `justify/space-between` where you don't really need to think about the layout (by adjusting cols spans).

But yeah, for structural layouts grids are better.


The Flexbox tutorial is pretty good. You know you've reached a difficult level when it starts throwing Estonian instructions at you.


Exactly this! It's not grid vs flexbox, it is grid AND flexbox.


Can you elaborate what constitutes as 1D and 2D in web layouts?


Laying out a set of tabs would be 1D (either horizontal or vertical). Laying out an page with headers, footers, and sidebars would be 2D (vertical and horizontal).


but headers, footers and sidebars are all trivial with flexbox. what's the advantage of grid in those cases?


Nope. You're probably abusing flexbox. This layout:

| HEADER | |Nav|Content|Sidebar| | Footer |

is more what we're talking about. You could do that, but it's not what flexbox was meant for. Try grid out. It will work easier for grid like layouts.


I know what layout you're talking about and it's trivial with flexbox. Why would you need a grid for that?


You don't _need_ grid, but it does make it simpler. You technically don't need flexbox either.

In grid you can define this layout in a single construct. Whereas with flexbox, you're defining several nested flex elements to get there.

You can think about the entire layout as a unit, rather than the horizontal parts first (sidebar/main content) then the vertical (header/footer) or vise versa.


Honest question, because I started with HTML when tables were still the rage for defining layouts and I pretty much stopped working on new sites shortly before Flexbox became a thing: Do people actually think that Flexbox is a nice API, or is it more like "well, at least it's better than using tables or float/clear hacks"? I know tables shouldn't be used for things that are not actually tabular data, but I have to say that just looking at them in the raw HTML document, they make it obvious how the page is going to be presented in the end. With Flexbox, you have an undefined maze of divs which are then magically styled by an external stylesheet. I recently tried using this approach for something that would probably have been solved with an image map 20 years ago, and it was awkward to work with. I see Flexbox can have an advantage when using the same markup for e.g. mobile and desktop layout, but just looking at the raw HTML always leaves me a bit confused how elements on the page will relate to each other.


Flexbox has been useful, but for me has essentially been superseded by css grid, pretty much for the reasons you mention. I find flexbox to be difficult to use and feels more like a stopgap feature on the way to full blown grids than anything long lasting. I wish subgrids would become standard, but regardless we're in a much better place these days vis-à-vis css layouts than we were pre-grid.


> just looking at them in the raw HTML document, they make it obvious how the page is going to be presented in the end

I guess you can say the same thing about the infamous <FONT> tag. But if you want styling information directly in the HTML, you can still do it with the "style"-attribute, using marginally more syntax. e.g. <div style="display:table"> or <div style="display:flex; flex-direction:row"> instead of table <table> where html table semantics are not appropriate.

I do find flexbox a much nicer model than tables, but I guess that comes down to taste. A flex is basically like a table with either a single column or a single row, and a bit more fine-grained control.


the style attribute is problematic with strong content security policies disallowing unsafe-inline styles [1]. This can be worked around using classes though.

[1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Co...


I find the flexbox syntax terrible and confusing, and the fact that they created a bunch of shortcuts that encompass several properties at once makes things even worse. Every time I want to use flexbox, I have to refer to the documentation. The result is that I use flexbox once for the main layout, and then tend to use other mechanisms in order to position small elements, menu items etc. even though flexbox would do the job perfectly.

I wish it was intuitive to me, so I could use it quickly and without turning my css code into a mess.


I also refer to the docs often, but I can get pretty much anything done with flexbox quite quickly. I guess it only comes down to practice.


Try Bootstrap 4's "grid only" CSS file. I used to do Flexbox by hand, until I realized I was reinventing the Bootstrap wheel by abstracting most of it into classes.

It's all based on rows and columns, that collapse based on screen width. Plus, utility classes for all the alignment positions.

You'll still run into the issue of way too many nested div's, but I find myself more productive than trying to flexbox everything by hand. ymmv.


CSS Grid is the nice API. It fits my mental model for 90% of layout use cases. Flexbox makes responsiveness a lot nicer, and it definitely passable.

> but just looking at the raw HTML always leaves me a bit confused how elements on the page will relate to each other.

Generally you shouldn't be able to determine layout from the raw HTML. HTML should be semantic. CSS determines layout and styling.


I somewhat disagree with this. The semantic structure should naturally define the layout.


Flexbox has its place in one's toolkit, but I still prefer floats in many situations. It might be subjective, but floats often seem to result in cleaner CSS, even taking into account the clearfix hack (which becomes much simpler with a Sass mixin).

Suppose you have the following desktop layout:

    ONE TWO THREE FOUR FIVE
and you want to turn it into the following mobile layout:

    O   N   E
    TWO THREE
    FOUR FIVE
With floats, you can achieve that by overriding only a few properties, primarily 'width'. But if you asked me to do it with either flexbox or grid, I'd have to think for a bit.

Flexbox is good for things that need internal flexibility in one dimension. Grid is for things that have a relatively static, two-dimensional layout. Floats are perfect for things that need to shuffle across dimensions, and I don't see any reason to avoid using them. After all, it's not as if floats are un-semantic or anything.


In your example, how are floats any different than a flex container with wrapping enabled? The wrapping is still dependent on the width of the children, just like your floating elements.


Two ways offhand:

* Float will alight "one" to the left or right with a gap next to it, while flex can stretch, center, or align the element differently.

* If the elements are different heights, they'll stack up very differently.


It's not different. Both will work. But if the above is all you need, I feel that flexbox adds a lot of verbosity for no benefit.


I think it is a common misconception that grid based layouts are static. Some combination of repeat, auto-* and minmax() can give very flexible layouts without even needing CSS media queries.


I think that that is part of the point with "modern" (however you want to call it) HTML: it should be declarative and layout-agnostic, and let the CSS do its thing regarding the various ways it should be displayed; this way the HTML is the same regardless of the actual layout of the page. Or at least it should be, in principle.


Just a reminder: csszengarden.com was created back in 2004 (I think). Zeldman's "Designing with Web Standards" came out in 2003. "Modern CSS" is over 17 years old. The CSS itself is not yet 24 years old.


It's not nice by any means.

I need to apply justify|align|content|items in the browser to make it do what I want. I can't for the life of me remember what they do.

But the underlying principles are neat. Flexbox gives me a container and an arbitrary number of children of various types which I can then position to my hearts delight. And things tend to fall in to place without me over-specifying every case.

As long as I'm working along one dimension, that is.

> but just looking at the raw HTML always leaves me a bit confused how elements on the page will relate to each other.

You say it like it's a bad thing. Chances are the relations are flexible.

One does run in to issues when the Flexbox rules apply across the bounds of components (e.g. Vue or React components) which makes composition difficult. Can be avoided by clearly separating layout from the rest. The S in SOLID applies to CSS as well.


> I need to apply justify|align|content|items in the browser to make it do what I want. I can't for the life of me remember what they do.

I found the Flexbox Zombies course to be helpful for that: https://flexboxzombies.com

It's free right now too.


I started at the same time as you. I can’t say it’s a nice API nor can you eyeball the document and understand its layout, but it’s better than the horror shows of centering things of old. Things like flexbox froggy allow it to become fairly intuitive.


Css specification does not do nice API. It does unintuive, convoluted and full of special cases. Flexbox is much better and easier then without flexbox.


Casual reminder that if you intend to support IE11(say for business use), Grid is completely unsupported.

Flex isn’t too bad and honestly really unlocks awesome abilities after you get used to it. Once you know flex, you can do the infamous “how to vertically center anything” move pretty easy.

Also, using order with flex is awesome. If you are using Bootstrap 4+ you can very easily use most flex properties responsively to do some crazy transforming layouts as well.


Actually IE11 has some support for grid layouts. Depending on your use case it might just be enough.

https://www.rachelandrew.co.uk/archives/2016/11/26/should-i-...


IE11 gets enough of grid support that it won't look absolutely terrible in most cases. Sufficient to get users by and maybe tell them to switch to a proper browser (ie, Firefox which has subgrid too)


A lot of people are posting their favorite links to flexbox and grid resources in this thread, so I'll post mine: two educational games designed to teach Flexbox and Grid.

https://flexboxzombies.com/

https://gridcritters.com/

They're extremely good and quite fun.


I was following along but after the first few code snippets it it says:

> You can see how nicely the div elements position itself horizontally. But if you notice, it doesn’t entirely take up all the space within the container. There’s a gap at the end.

There's no example outputs or screen shots or preview panes or anything so no, I don't "see".

I guess I'm supposed to be copying this code by hand into a CodePen or a sample HTML page but that wasn't made clear at the beginning. I started reading expecting an article explaining something but it turns out that it's a half-tutorial.

Luckily, people have posted a bunch of great links in these comment so I'm going to go and read those instead.


The thing that's a tiebreaker for me is grid-gap (and recently, its shorthand gap). Uncountable hours have been wasted making two elements separate from each other for a few pixels. Still today, the techniques used by Bootstrap are still used, altough a bit less hacky with calc(), but still we're relying a lot on negative margins.

With gap, making a gutter is trivial. And while gap _can_ be used with flexbox, the thing is that it's not supported by Safari[1], and who knows when it will be implemented.

1: https://caniuse.com/flexbox-gap


CSS Grid is nicer for large layouts, and it’s nice to change one piece of text and change your layout, especially if you’re living in your CSS file only. And from time to time I’ve relearnt it and got excited about it. But it’s unwieldily; the shorthand syntax is nice but it still feels unpleasant when I’m still editing the HTML - when I’m quickly laying out things I still revert to putting flexbox rules in DOM elements for development speed.


The best tutorials I've seen for both Flexbox and Grid are from Kyle at Webdev Simplified. Seriously check out this dude's channel. He explains everything perfectly.

Flexbox: https://youtu.be/fYq5PXgSsbE

Grid: https://youtu.be/9zBsdzdE4sM


My kingdom for grid-gap support with flexbox.


I just had to fix a bunch of css yesterday because someone forgot we still need to support IE11! For the exact same issue!


I created a decent reference for myself so I didn't have to do a web search whenever I forgot the name of one of the property values:

https://dwayne.xyz/utils/flexbox-css-grid


> CSS grid works with a 12-grid arrangement, where the screen is (invisibly) divided into 12 parts, and items must fit into this arrangement.

Is the '12-grid arrangement' part of CSS or just a convention used by current web devs? [I'm a curious back-end dev.]


12 is just a good number for dividing up the screen that supports common column based layouts. 1-4 columns is a cinch.


Yes, it's almost like a standard, but it is optional. Some people like 16 columns. I personally use 12 but have used 16 in a project that required smaller segments.

This comes from paper design, as usual, and I don't think 12 was the number. It's just a number that makes sense for desktop screens (where it began).


Both CSS Grid and Flexbox are powerful in their ways. Before deciding which to choose, understand the complexity, the structure and the content of the site you are to build.


> A good layout makes users stay on a site because it makes important stuff easily accessible and intuitive to find. A lousy layout frustrates users, who leave because they can’t find what they are looking for.

On a website with 2 pop-ups going straight to your face when you open it (and the cookie-related one isn't even GDPR compliant) >_<.


Por que no los dos?


My rule of thumb: flex


My rule of thumb: keep learning.


I just never come across a situation where grid would be better than flex ...


amen to this. i've tried both flex and grid and grid was so overly complicated. flex is simple and has always worked for me even on mobile.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: