CSS · Layout and visual systems
How do container queries work?
Short answer
Container queries let a component respond to the size of an ancestor container instead of the viewport. You declare a containment context with container-type, then query it with @container.
A container query needs an ancestor that establishes a query container. The element itself cannot be its own container; its descendants query the nearest eligible ancestor with a matching name or type.
.card-wrap {
container-type: inline-size;
container-name: card;
}
@container card (min-width: 30rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
}
}Key details
- container-type: inline-size establishes inline-size containment
- container-name lets you target a specific ancestor
- Container query length units such as cqw and cqh refer to the query container
- Only descendants can query a container, not the container itself
- A container cannot be sized by its descendants on the contained axis
This is the component-level counterpart to media queries. A card can switch to a horizontal layout when its own container is wide, even if the viewport is narrow because the card sits in a sidebar.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between a media query and a container query?
- 2Why can an element not query itself?
- 3What does container-type: inline-size do?
- 4What are cqw and cqh units?
Say it in the interview
Container queries let a component respond to its container rather than the viewport. I put container-type on an ancestor, optionally name it, then use @container to change the component's layout. That is ideal for reusable cards that appear in different widths. The trade-off is containment, so I choose the wrapper deliberately and remember that an element cannot query itself.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live CSS mock interview and get scored feedback on depth, clarity and confidence.