For over a decade, responsive design relied exclusively on viewport media queries. However, modern web applications are assembled from modular components (cards, profile badges, chat widgets). A card component placed inside a narrow sidebar needs a stacked layout, while the exact same card placed in the wide main feed needs a horizontal layout. CSS Container Queries (@container) solve this permanently.
To use container queries, you must first register a parent element as a containment boundary using container-type:
/* 1. Register the parent element as a Query Container */
.card-wrapper {
container-type: inline-size; /* Query container width */
container-name: cardContainer;/* Optional semantic name */
}
/* 2. Default Base Layout (Vertical Stack for narrow spaces) */
.product-card {
display: flex;
flex-direction: column;
gap: 12px;
}
/* 3. When the CONTAINER is >= 450px wide (NOT viewport!) */
@container (min-width: 450px) {
.product-card {
flex-direction: row; /* Automatically switches to side-by-side! */
align-items: center;
}
}
Container queries also unlock dedicated sizing units relative to the container itself:
• 1cqw: 1% of the query container's width.
• 1cqh: 1% of the query container's height.
.card-title {
/* Font size scales directly with card size, anywhere on the page! */
font-size: clamp(1rem, 5cqw, 2rem);
}
Boost your CSS and front-end development proficiency by exploring these closely connected topics:
Understand margins, borders, padding, content and the universal box-sizing fix.
Master 1D alignment, justify-content, align-items, flex-wrap and responsive flow.
Build powerful two-dimensional grid layouts with template areas and fr units.
Eliminate styling conflicts and master selector weights from 0,0,0,1 to !important.