Making sense of container query

| permalink | css

Reproduced from Stackoverflow

Containers can't be sized by their contents, and inline elements can't be containers

There are a few things going on here:

  1. container-type: inline-size applies various types of 'containment' to the element, including inline-size containment.

    Size containment 'turns off' the ability for an element to get size information from it's contents. That's important for container queries, since it breaks the 'infinite loop' where a container query changes the content size, which changes the query, which changes…

    So the container size has to come from either from context (eg block elements stretch by default, elements in grid flex can also stretch, etc) or explicit sizing in CSS. Outside of those cases, elements with size containment will collapse. Since inline-block elements like buttons shrink-wrap to their contents, and size containment removes content-sizing, they collapse by default. Put them into a flex or grid, or add block display, and they'll stretch to fit their context.

  2. Size containment doesn't work on inline elements (unless they are 'atomic inlines', eg images and videos and stuff without other content).

    Using an inline element as a container just isn't going to work. You can still use a span, just have to give it a non-inline display. This should be shown as a non-applied style in browser devtools, but I guess it isn't yet. I hope browsers clarify that.

So all your code is behaving according to spec. The fact that containers have to ignore their content size is the main reason we don't just make everything a container. It's also the trick that was required to make Container Queries work at all.