Ad space (banner)
🎨HTML & CSS Lessons
Lesson 43 / 50

Switching Layouts Per-Component with Container Queries

In this lesson you'll learn how to switch layouts per component using container queries, so you can design components that are easy to reuse. This is for people searching "CSS container query usage."

Using @container (a container query) lets you change a style based not on the overall screen width, but on "that component (container)'s own width." This is handy when you want the same card component to look good whether it's placed in a narrow spot or a wide one.

The sample code registers .wrapper as a container with container-type: inline-size;, and switches the card's layout from stacked to side-by-side inside @container (min-width: 400px). Try changing the width of .wrapper and confirm how the switching point moves.

A common beginner stumbling block is that using a container query requires first registering the parent element as a container by specifying container-type. Forgetting this means the @container rule won't work correctly.

A traditional media query could only look at the entire screen's width, but since a container query can judge on a per-component basis, it makes the same component much easier to reuse in different places. This is a relatively new CSS feature that's been getting attention.

HTML & CSS
OUTPUT

💡 The preview runs entirely on this page — nothing is sent externally.

Ad space (banner)
Ad space (in-article)