CSS Grid

Image of Author
September 26, 2022 (last updated July 20, 2023)

A great resource for learning about CSS Grids is https://css-tricks.com/snippets/css/complete-guide-grid/

CSS Grid is not magic, it's just an improvement. The most disappointing thing was realizing that it wasn't a "magic columns solution" where I could declare a few columns for full-page layout and then magically have each column take a variable number of grid elements and lay those elements out internally with flexbox.

Grid cells aren't designed for multiple elements

You can't put multiple elements into a single grid cell. Well, you can, but they will overlap.

I was hoping to use CSS Grid to creating a flexible, columnar layout for full pages. Three columns for wide screens, two for medium, and one for mobile (you can do this, but not also what comes next). I wanted content from different columns to "join" other columns as the screen width shrunk. For example, on large screens I'd have left-side-content, main-content, and right-side-content. Then, on medium screens I'd get rid of the left-side completely, and move left-side-content underneath right-side-content. You cannot do this, as far as I can tell. The closest you can get is giving both elements the same grid-area name, but then they overlap.

The workaround that I am using is the typical strategy of creating multiple components and hiding and revealing those components at different screen sizes to give the illusion of movement. I call this The Secret Twin Layout Strategy.

Grid area minimum width is, sometimes, counterintuitive

Grid content might overflow its grid area when it doesn't make sense. This is because min-width of a grid element is set to auto. min-width: auto is a browser defined behavior.

I was struggling with this and finally found clarity reading Breaking the Grid By Dave Rupert on the grid overflow issue:

Typically overflow-x: auto fixes horizontally overflowing elements. But nope, not here. The next escalation is to wrap the element and try a bunch of overflow: hidden tricks to force the layout to obey. Still nope.

The reason this is happening is that Grid Items have a default min-width: auto and will auto-size to the content inside. It sets its min-width based on the width of overflowing block. So to fix an deeply nested overflowing child, you counter-intuitively ignore the parent element and go all the way up the DOM tree to the Grid Item and zero-out the min-width.

.grid > * { min-width: 0; }

This will result in Grid Items with overflowing content to be sized correctly. But not always…

Heavy-lifting layout grids need to be agnostic of the content inside of them and tolerant to support a wide variety of scenarios. I’ll likely need to include this on every project to make Grid Items as tolerant as possible. While not a bug, I can see this as being “Clearfix 2.0” territory.