My card component looks fine in a wide main column but breaks in a narrow sidebar, even on a large screen, because media queries only look at the viewport. Can the card respond to its own container width?
#css#container-queries#responsive
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
My card component looks fine in a wide main column but breaks in a narrow sidebar, even on a large screen, because media queries only look at the viewport. Can the card respond to its own container width?
#css#container-queries#responsive
Yes: container queries (supported in all current evergreen browsers).
1. Mark the parent as a container
.card-wrap {
container-type: inline-size; /* track width only */
container-name: card; /* optional */
}
2. Query the container
.card { display: grid; gap: 1rem; }
@container card (min-width: 480px) {
.card {
grid-template-columns: 160px 1fr;
}
}
The card switches to a two column layout whenever its container is at least 480px wide, wherever it is placed.
Container query units
Inside a container, cqw, cqi and friends are relative to the container size, for example font-size: clamp(1rem, 4cqi, 1.5rem).
Tailwind 4
Container queries are built in:
<div class="@container">
<div class="grid gap-4 @md:grid-cols-[160px_1fr]">
...
</div>
</div>
Variants like @sm, @md, @lg map to container widths; @max-md: is the max version. On Tailwind 3 you needed the @tailwindcss/container-queries plugin.
Media vs container queries
prefers-reduced-motion, prefers-color-scheme).Pitfalls
container-type on a wrapper.container-type: inline-size applies containment, so the container's width can no longer depend on its children; give it a width from its layout.container-type on the element that must also be styled by the query.