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:
One-column
+---------------+
| ========= |
+---------------+
| ========= |
+---------------+
| ========= |
+---------------+
| ========= |
+---------------+

Two-column:
+---------+---------+
| ==== | ==== |
+---------+---------+
| ==== | ==== |
+---------+---------+
One-column
+---------------+
| ========= |
+---------------+
| ========= |
+---------------+
| ========= |
+---------------+
| ========= |
+---------------+

Two-column:
+---------+---------+
| ==== | ==== |
+---------+---------+
| ==== | ==== |
+---------+---------+
Is there any way to do this sensibly intrinsically, or do I need to resort to media queries?
10 Replies
curiousmissfox
curiousmissfox•2mo ago
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 result
prophile
prophileOP•2mo ago
But how do I only do that if it's in the two-column layout?
Chris Bolson
Chris Bolson•2mo ago
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).
Jochem
Jochem•2mo ago
"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
prophile
prophileOP•2mo ago
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
Chris Bolson
Chris Bolson•2mo ago
But you have already defined a min width for your grid columns to tell it when to wrap the columns, haven't you?
prophile
prophileOP•2mo ago
max-content
Chris Bolson
Chris Bolson•2mo ago
ah, sorry, you are right, it isn't quite so simple as knowing the min column width 🤔
prophile
prophileOP•2mo ago
A container query is probably the pragmatic option, you're right
curiousmissfox
curiousmissfox•2mo ago
Yes a container query is probably the right approach given your constraints

Did you find this page helpful?