CSS Container Queries: How Browsers Calculate and Recalculate Styles
Ever had a layout break because a component looked perfect on your screen but warped on a colleague’s? Or tried to build a responsive widget that adapts to its container , not just the viewport , only to realize CSS media queries don’t cut it? That’s exactly where CSS container queries come in. They let you apply styles based on the size of a container element instead of the whole viewport. It…
CSS container queries are a new feature that let you apply styles based on the size of a container element, not just the viewport. This can help make responsive widgets that adapt to the container's size, not just the viewport. However, there are a few tricks browsers use to figure out when to apply those styles.
Imagine a card inside a sidebar. When the sidebar is narrow, the card's content might look different than when the sidebar is wide. With container queries, you can write CSS like this:
.card {
container-type: inline-size;
}
@container (min-width: 300px) {
.card {
display: flex;
flex-direction: row;
}
}
The browser knows when the container size crosses the 300px threshold and applies the new styles.
How do browsers detect these container size changes? They don't constantly measure everything on every frame, that would be too slow. Instead, they use a few tricks:
1. They watch for intrinsic size changes, like when the content itself grows or shrinks.
2. They implement something similar to the Resize Observer API, which detects size changes on container elements.
3. They cache container sizes and only trigger reevaluation if the sizes actually differ.
When a container size changes, the browser schedules a style recalculation. It looks at the styles applied to container queries inside that container and updates them if needed. This can trigger a layout update for those elements and their children, and then repaint the updated parts.
There are a few things to keep in mind when using container queries:
1. Make sure your container element has the container-type property set. Without it, container queries won't work.
2. Check the container's actual size in DevTools. Padding, borders, and box-sizing can affect the size.
3. Understand the container sizing modes. The most common is inline-size, which watches width in horizontal writing modes. If your container only reports inline-size but you're using block-size conditions, those queries won't match.
4. Be careful with nested containers. Each nested container is tracked separately, so styles inside them can re-trigger layout.
5. Avoid layout thrashing. Don't create container query rules that increase container size when the container is already near your breakpoints.
6. Use Resize Observer in your JavaScript code to watch container sizes and log when they change.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.