3 ms·
Question from a CSS noob, When would you use Flexbox vs Grid?
by victor106 3y ago
Question from a CSS noob, When would you use Flexbox vs Grid?
- doytch 3y agoMy personal heuristic: - Start with Flexbox. Flexboxes of flexboxes will solve almost everything that’s common, and be easier to reason through and maintain imo. - If you’re doing something that appears tabular, use Grid. Flexbox will appear as though it’ll get you there, but the moment you start having cell contents that are highly variable in size your columns will start to get out of sync. - The above is esp the case if you’re trying to do repeating sets of rows. Eg Row type A, row type B, A, B, etc. That’s a Grid problem. But of course, the only way to get good mental models is by trying both approaches and seeing what the drawbacks are. Maybe try the Grid games that folks have linked in other comments?
- dsego 3y agoFlexbox for most stuff, resort to grid only if flexbox can't solve your layout. The way I see it, if there is horizontal or vertical stacking, it's flexbox. And since you can nest, it covers a wide ranged of typical layout patterns (boxes within boxes). One caveat, since flexbox only arranges vertically or horizontally, you have to insert container flex elements, which means it affects the markup, so you are a bit constrained if you want to make it really responsive and rearrange everything based on viewport size. Grid is more complex, and useful for fixed layouts when things have to align more. With sub-grid support it will be even more powerful.
- moron4hire 3y agoI tend to default to grid, especially for the top level page layout. I did it easier to reason about how it's going to look by just configuring the container. Less styling has to be specified for the child elements, especially when defining named areas.
- emadda 3y agoThe reasons I sometimes use grid over flex: - You can align things in 2D space, not just along a single axis (like flex). Great for the top level layout of a site/UI. - You can have white space. I often create white space (empty grid cell) in my UI so I can add UI elements there if needed later on. Works well with elements that are conditionally rendered, as these will change flex layouts but elements assigned to a grid cell will not move.
- gardenhedge 3y agoGrid can do 1D (horizontal or vertical) or 2D (horizontal and vertical simultaneously). Flexbox can just do 1D (horizontal or vertical). So if you wanted, you could just use Grid... although Flexbox could be considered slightly more striaghtforward for 1D stuff.
- marcosdumay 3y agoFlexbox aligns things while grid mostly allocates specific space for them. So, if I need alignment, I go with flexbox. If I have all the elements sketched-up in a design, I go with grid.