tezvyn:

When container queries beat media queries

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

understanding of component-level responsiveness.

OUTLINE

media queries react to viewport, container queries react to a parent's size, ideal for reusable components; set container-type on an ancestor then query it.

WHAT THIS TESTS: This evaluates whether you can reason about responsiveness at the component level and know the mechanics of declaring and querying a container.

A GOOD ANSWER COVERS: Media queries respond to the viewport or device, so the same component looks identical regardless of the slot it occupies. Container queries respond to the size of a designated ancestor, which is what you want for design-system components reused in many layouts. The classic scenario is a card or product tile that should switch from a stacked to a side-by-side layout based on whether it is placed in a roomy main area or a cramped sidebar, independent of the overall window size. You establish a query container by setting container-type, most commonly inline-size to query width, on the ancestor, and you may add container-name to target it specifically. Then @container (min-width: 400px) rules apply to descendants based on that container's measured size.

COMMON WRONG ANSWERS: Saying container queries replace all media queries; viewport-level concerns like page-wide breakpoints still suit media queries. Attempting to style the container element itself with its own container query, which causes a layout dependency loop the spec forbids; you query from inside. Forgetting container-type, so @container never matches.

LIKELY FOLLOW-UPS: What is the difference between inline-size and size containment, and why does size containment require an explicit height. How do container query units like cqi and cqw work. How do you handle browsers without support.

ONE CONCRETE EXAMPLE: Wrap each card in a .card-wrapper with container-type: inline-size. Inside, write @container (min-width: 350px) { .card { display: grid; grid-template-columns: 120px 1fr; } }. Drop the same card into a narrow sidebar and it stays stacked; drop it in the wide main column and it goes side-by-side.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.