Topic 26 of 30
Container
Overview
Container queries apply styles based on the size of a parent container rather than the viewport. This enables truly reusable components that adapt to their context — a card in a narrow sidebar looks different than the same card in a wide main column.
Syntax
css
/* 1. Define a containment context */
.card-wrapper {
container-type: inline-size;
container-name: card;
}
/* 2. Query the container */
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 200px 1fr;
}
}
@container card (max-width: 399px) {
.card {
display: flex;
flex-direction: column;
}
}
/* Container query units */
.card { font-size: 1cqi; } /* 1% of container inline size */Common Pitfalls
- Container queries require container-type on the PARENT — the query runs on the containing element, not the styled element.
- You cannot query a container from itself — only descendants can respond to a container query.
- Interview tip: Container queries solve the problem where you need a component to look different in a sidebar vs main content — viewport media queries can't do this.
Real-World Example
A product card that adapts to narrow sidebar vs wide main column:
example
css
/* Container context */
.card-container {
container-type: inline-size;
container-name: product-card;
}
/* Base styles — mobile/narrow */
.product-card {
display: flex;
flex-direction: column;
border-radius: 12px;
overflow: hidden;
}
/* Wide container — horizontal layout */
@container product-card (min-width: 360px) {
.product-card {
flex-direction: row;
}
.product-card img {
width: 40%;
object-fit: cover;
}
}
/* Very wide — show extra details */
@container product-card (min-width: 500px) {
.product-card .description { display: block; }
.product-card .buy-btn { width: auto; }
}