Understand CSS container queries and use them to create reusable cards, panels and interface components that respond to available space.

Why viewport breakpoints are not always enough

Traditional media queries respond to the browser viewport. That works for page-level layout, but a reusable component may appear in a narrow sidebar, a wide content column or a modal on the same screen. Its ideal layout depends on the space allocated to it, not just the overall window width.

Establish a query container

Give the parent element a containment context with a rule such as `container-type: inline-size`. You can also name it with `container-name` when a component contains nested elements and you want the query to target a particular ancestor. The child can then use an `@container` rule to change its layout when the container reaches a suitable width.

Make a component change its own composition

A card might stack its image and text in a narrow container, then switch to a horizontal arrangement when there is enough room. Keep the default style useful at the smallest size and introduce changes progressively. Avoid choosing breakpoints solely because they match familiar device categories; measure where the content actually becomes cramped.

Keep container queries focused

Use them for component-level decisions such as grid columns, spacing, typography and image placement. Use media queries for page-level concerns such as global navigation or viewport-specific behaviour. Combining both tools gives a clearer division of responsibility.

Provide a robust fallback

Container queries are supported in modern browsers, but a progressive enhancement mindset is still valuable for projects with older browser requirements. Ensure the base layout remains readable without the enhanced arrangement. Do not make essential content dependent on a particular query state.

Test components in realistic contexts

Preview each component at several container widths, including awkward intermediate sizes. Test long headings, translated labels, large text settings and images with different aspect ratios. A component that works in a full-width demo may fail when placed in a real sidebar.

Final review

Before applying these recommendations to a live website, make a backup where relevant, test changes in a safe environment and verify the result on desktop and mobile devices.