Fun Times With Sizing Grid Elements

0
21

Chris showed us a little while back that CSS grid areas and their elements are not necessarily the same size. It’s an interesting point because one might assume that putting things into a grid area would make those things occupy the entire space, but grid areas actually reserve the space defined by the grid and set the element’s justify-content and align-items properties to a stretch value by default.

So… yes, they are the same size, but not necessarily.

Chris ended his post by asking “who cares?” while indicating no one in particular. The point was much more geared toward calling this out as a starting point for folks who need to align content in the grid.

I’m not sure I have a better answer, but it made me think it would be fun if we could leverage those auto-assigned stretch values to adapt a user interface in interesting ways.

I’m not saying any of these are great use cases. In fact, they may be downright silly. That said, maybe they can be the starting point for other ideas.

Stretching Form Fields

One idea is to add some interaction to form fields. If our <form> is the grid container then we can set text inputs where they start at their default width using the start value and then expanding them to the full width of the container by switching to the stretch value on a :focus state:

.grid__form {
display: grid;
}

.grid__input {
justify-self: start;
}

.grid__input:focus {
justify-self: stretch;
}

See the Pen CSS Grid: Grid Child Stretch on Focus by Geoff Graham (@geoffgraham) on CodePen.

Then again, we can already do something similar with Flexbox but with the benefit of the flex being an animated property:

See the Pen Flexbox: Child Stretch on Focus by Geoff Graham (@geoffgraham) on CodePen.

I’m honestly not sure where expanding form fields on focus would make for great UX but it’s certainly fun to play with.

Curtain Opening Effect Re-Visited

We posted a good ol’ fashioned CSS trick last year that uses the checkbox hack to create the effect of a curtain opening to reveal content behind it.

See the Pen OXJMmY by Geoff Graham (@geoffgraham) on CodePen.

That used widths and positioning to move things around on click, but we could have done something similar with Grid. Again, this is less robust because it lacks animation and the does not allow the curtain to fully open, but it does show how we can leverage the stretch, start and end values of a grid element and its sizing to achieve some interesting ideas.

See the Pen CSS Grid Curtain Reveal by Geoff Graham (@geoffgraham) on CodePen.

What Else?

The fact that grid elements are not always the size of the grid area is a nice tip to keep in our back s as we develop layouts. I’d bet we can come up with more ideas to take that concept to another level and have fun with it as a group. Share ’em if you have ’em!