Media queries respond to the viewport. Container queries respond to an ancestor container.
That difference matters for components. A card might be wide in the main column and narrow in a sidebar on the same page.
Create a query container
First, declare a container:
.course-card {
container-type: inline-size;
}
Then query it:
@container (width >= 32rem) {
.course-card__body {
display: grid;
grid-template-columns: 10rem 1fr;
gap: 1rem;
}
}
The card changes when its container is wide enough, not when the viewport is wide enough.
Named containers
Use names when you need to target a specific ancestor:
.course-card {
container: course-card / inline-size;
}
@container course-card (width >= 32rem) {
.course-card__title {
font-size: 1.5rem;
}
}
Names keep queries clear when nested components each define containers.
Container units
Container units are relative to the query container:
.course-card__title {
font-size: clamp(1.125rem, 6cqi, 1.75rem);
}
Useful units:
cqi: 1% of container inline sizecqb: 1% of container block sizecqw: 1% of container widthcqh: 1% of container heightcqminandcqmax: smaller or larger container dimension
Prefer logical units like cqi when writing direction should not matter.
Fallbacks and support
Size container queries are broadly usable in modern browsers. Some newer container query types, such as scroll-state queries, have more uneven support.
Use progressive enhancement when needed:
.course-card__body {
display: grid;
gap: 1rem;
}
@supports (container-type: inline-size) {
.course-card {
container-type: inline-size;
}
@container (width >= 32rem) {
.course-card__body {
grid-template-columns: 10rem 1fr;
}
}
}
The base layout works everywhere. The container-aware layout improves it where supported.
Preview
Product card
Generated CSS
What to carry forward
- media queries respond to the viewport
- container queries respond to an ancestor container
- declare a container with
container-typeorcontainer - use container queries for reusable components
- container units like
cqimake sizing follow component context - use
@supportswhen relying on newer or unevenly supported features
Quick Check
One answerA card appears in both a narrow sidebar and a wide main column at the same viewport width. Which query is usually better for changing the card layout?
Choose the best answer and use it to track your progress through the lesson.
Why that answer is correct
The card's own available space is the important condition, so a container query matches the problem.
The next lesson covers logical properties and modern sizing tools that make responsive CSS more adaptable.