Dynamic justification based on intrinsic column count
Hello folks! I'm layout something out with CSS Grid: four items. I'm going for a two-column layout on wider viewports, and one-column on narrow viewports. So far so good, including making the switchover intrinsic rather than resorting to media (or container) queries.
The sticking point is that I'm looking to justify the items separately in the two cases. For the one-column layout, I want the items centered or stretched (not fussed either way), but for the two column layout I'd want the left column right-aligned and the right column left-aligned.
ASCII art demonstration:
Is there any way to do this sensibly intrinsically, or do I need to resort to media queries?
10 Replies
Until we have support for attr() , on desktop you can set the grid to
justify-items: start;
then for the two items in the 2nd col, youll have to specifically set justify-self: end ;
Alternatively you can set the items in col 2 to use margin-inline-start: auto;
instead of justify-self. Same resultBut how do I only do that if it's in the two-column layout?
I don't know if this is possible without, as you say, a media or container query.
Why do you want to avoid using a container query?
All you need to do is define a container query where the width is less than your minimum grid column width (taking into account padding and gap).
"resorting" is the wrong way to look at media queries. Using media or container queries isn't a failure of coming up with a more clever solution. They're a tool to use when they're convenient
A fair point
I'd prefer not to be guessing with the break-point and use intrinsic sizes of the content in case they change
But you have already defined a min width for your grid columns to tell it when to wrap the columns, haven't you?
max-content
ah, sorry, you are right, it isn't quite so simple as knowing the min column width 🤔
A container query is probably the pragmatic option, you're right
Yes a container query is probably the right approach given your constraints