container queries or a resize hook for a card that is 240px or 900px wide Layout
Same card component, two contexts. In the sidebar it is 240px wide and needs to stack. On the main page it is around 900px and should be a row with the meta on the right.
I already have a useElementSize hook in the codebase from something else, so using it is close to free. But it feels like the wrong tool and I cannot articulate why beyond vibes. Convince me either way.
@serger_seth · 3mo ago · 3 replies
Container queries, and it is not close.
The hook means your first render is wrong, then you measure, then you re-render. On a server-rendered page that is a visible layout shift on every load, and it is a shift that happens after the user has already started reading. You also re-render the component on every resize, and you cannot render the correct layout on the server at all because the server does not know how wide anything is.
In v4 the variants are built in. Put
@containeron the wrapper, then@sm:flex-rowon the child, or@min-[380px]:when you need a specific number rather than a scale step. No JavaScript, correct on the first paint, works inside a modal you have not built yet.The hook is the right answer for one thing only, which is when the decision is not really about width.
Reply
Report
@thea_mandel · 3mo ago
One gotcha: the container has to be an ancestor, not the element you are querying, and turning something into a container changes how it sizes. If your wrapper collapses to nothing the moment you add it, you asked for full containment when you wanted
inline-size.Reply
Report
@hemline_hana · 3mo ago
Name your containers from day one -
@container/cardand@lg/card:- otherwise the first time you nest a card inside another card the inner one starts answering to the wrong ancestor and the bug looks like magic.Reply
Report