Sub topic 1
Why Viewport Media Queries Fall Short for Components
A component is a self-contained piece of interface, such as a product card, a comment, or a stats widget. You build it once and place it in many different spots. Viewport media queries have been the standard tool for responsive CSS for over a decade, but they measure the wrong thing for components. This chapter explains why, using one concrete example, and sets up the idea that the rest of the tutorial builds on.
Prerequisites
This chapter assumes you are comfortable with the following:
- Core CSS: selectors, the cascade, and the box model.
- Basic layout with flexbox or CSS grid.
- Writing
@mediaqueries withmin-widthandmax-width. - CSS custom properties (
--nameandvar()). They matter in later chapters, not this one.
You do not need any knowledge of container queries. This chapter only describes the problem.
What a media query measures
A media query tests facts about the environment the page is displayed in. The most common test is viewport width, which is the width of the browser window (or of the screen on a phone).
@media (min-width: 700px) {
.card {
grid-template-columns: 8rem 1fr;
}
}This rule applies whenever the viewport is at least 700px wide. Nothing in it refers to .card itself. The condition is about the window, and it is the same for every element on the page. The rule selects .card, but it cannot ask how much room that card has.
That distinction does not matter when a component always takes a fixed share of the page. It starts to matter once the same component can appear in places of different widths.
A card that works in one place
Here is a simple card with an image and some text. The card is mobile-first: it stacks the image above the text, then switches to two columns on wide viewports.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Card with a media query</title>
<style>
.layout {
display: grid;
gap: 2rem;
padding: 1rem;
}
@media (min-width: 900px) {
.layout {
grid-template-columns: 1fr 18rem;
}
}
.card {
display: grid;
gap: 1rem;
padding: 1rem;
border: 1px solid #ccc;
}
.card img {
width: 100%;
height: auto;
}
@media (min-width: 700px) {
.card {
grid-template-columns: 8rem 1fr;
}
}
</style>
</head>
<body>
<div class="layout">
<main>
<article class="card">
<img src="https://placehold.co/300x200" alt="Placeholder">
<div>
<h2>Main column card</h2>
<p>This card has plenty of room.</p>
</div>
</article>
</main>
<aside>
<article class="card">
<img src="https://placehold.co/300x200" alt="Placeholder">
<div>
<h2>Sidebar card</h2>
<p>This card has very little room.</p>
</div>
</article>
</aside>
</div>
</body>
</html>Look at the main column first. Below 900px it fills the screen. Above 900px it shares the row with an 18rem sidebar. The card's 700px breakpoint was chosen with the main column in mind, and it behaves well there.
The same card in a sidebar
The page above also puts a card in the sidebar. The sidebar is 18rem wide, which is 288px at the default font size. After padding and the gap, the card's content area is even narrower.
Now consider a viewport that is 1200px wide:
- The
min-width: 700pxrule matches, because 1200 is at least 700. - The sidebar card switches to a two-column grid with an 8rem image column.
- Only a few rem remain for the text, so the headline wraps after every word or two.
The card has about 250px of room, but it received the layout meant for a wide space. The media query had no way to know. It saw a wide viewport and applied the wide layout everywhere.
The reverse also happens. Between 700px and 900px the sidebar is not yet beside the main column, so the card is full width. Everything is fine there. At 900px the sidebar appears and the card shrinks, and no media query fires, because the viewport is still wide.
The viewport width is the same for both cards, so the query result is the same for both. The card's available space is what differs, and the query cannot see it.
Common workarounds and what they cost
Developers have worked around this for years. Each approach solves part of the problem and adds its own burden.
- Context-specific selectors inside media queries. You write
@media (min-width: 700px) { main .card { ... } }and leaveaside .cardalone. The card now depends on where it lives, so it is no longer a reusable component. Every new placement needs new CSS. - Modifier classes. You add
.card--compactand apply it by hand in the sidebar. This works, but the author of each page must remember which variant fits which slot. When the layout changes, the classes must change too. - JavaScript with
ResizeObserver. A script measures the element and toggles a class. This is accurate, but it runs after layout, can cause a visible flash or an extra layout pass, and does nothing before the script loads. - Intrinsic layouts. Techniques like
flex-wrap,grid-template-columns: repeat(auto-fit, minmax(...)), andclamp()let content respond to its space without queries. They are often the best choice, but they cannot express every change. For example, they cannot hide a secondary line of text or swap a vertical layout for a horizontal one at a chosen width.
| Approach | Reusable in any slot | Reacts to real space | Needs JavaScript |
|---|---|---|---|
| Viewport media query | No | No | No |
| Context-specific selectors | No | Indirectly | No |
| Modifier classes | Only by hand | Indirectly | No |
| `ResizeObserver` | Yes | Yes | Yes |
| Intrinsic layout | Yes | Yes | No |
The last two rows show what we want: a component that reacts to its real space, works in any slot, and needs no script. Intrinsic layout gets there for simple cases. Container queries extend it to cases that need an explicit condition.
What a component actually needs to know
A component should depend on its own context, not on the page. The question a card should ask is "how wide is the space I was given?" The answer depends on several things at once:
- The page layout, such as a sidebar that appears at 900px.
- The parent's own rules, such as a grid track set to
18rem. - Padding, gaps, and borders between the viewport and the card.
- Other instances of the same component on the same page.
The last item is the clearest case. If a dashboard shows four cards in a row at one moment and one card per row at another, the layout system knows each card's width. A viewport query only knows the window.
A viewport query would have to predict every one of these factors. That prediction breaks whenever someone changes the layout, even when the component's own CSS is unchanged. The component's CSS and the page's CSS become coupled through a number such as 700px, which means nothing by itself.
A first look at the alternative
Container queries solve this by letting a rule test the size of an ancestor element instead of the viewport. You mark one ancestor as a query container, then write rules against it:
.card-wrapper {
container-type: inline-size;
}
@container (min-width: 400px) {
.card {
grid-template-columns: 8rem 1fr;
}
}Here .card switches to two columns when its wrapper is at least 400px wide, whether the window is 360px or 2000px wide. The same card in the sidebar and in the main column now makes separate decisions. Later chapters explain each part of this snippet. For now, notice that the 400px threshold describes the component's own needs.
Where media queries are still the right tool
A viewport query is correct when the thing you are testing really is a property of the viewport or the user's device. Keep using @media for these cases:
- Page-level layout. Deciding whether the sidebar appears beside or below the main content is a decision about the whole page. A container query would have nothing meaningful to measure there, because the outermost layout has no wrapper to ask.
- User preferences. Conditions like
prefers-reduced-motion,prefers-color-scheme, andprefers-contrastdescribe the user, not a box on the page. - Input and display capabilities.
hover,pointer,resolution, andorientationdescribe the device. - Print styles.
@media printswitches the whole document into a different medium.
A useful rule of thumb is this: if the answer is the same for every element on the page, use a media query. If the answer depends on where an element sits, use a container query.
Gotchas when reasoning about the problem
- A breakpoint is not a property of the component. If you write
700pxin a component's CSS, check whether 700px is really the card's minimum comfortable width. Often it is the viewport width at which the main column happened to be wide enough. That is a fact about one page. - Browser zoom and large text change the numbers. Zooming to 200% halves the CSS width of the viewport, so media queries respond. A component in a fixed-width sidebar does not get narrower, but its text gets larger and may now overflow. Media queries on the viewport can't express "this box got tight."
- Testing at a single viewport hides the bug. The sidebar card above looks fine at 600px and 800px. It is only wrong between 900px and about 1100px, where the sidebar has appeared but the viewport still passes the card's breakpoint. Check components at several viewport widths and in every slot where they can appear.
- Embedded and user-resizable contexts. Components shown in a resizable panel, a dialog, or a CMS block have widths that depend on content, not on the window.
Exercise
A product card uses @media (min-width: 700px) to switch to a two-column layout. It looks correct in the main column. On a 1200px-wide viewport, the same card is cramped in an 18rem sidebar. Explain why the media query cannot fix this, and name one way to decide whether to use a media query or a container query for a given rule.
Show answer
The media query tests the viewport width, which is 1200px for every element on the page, so it matches for both the main column card and the sidebar card and applies the two-column layout to both. It cannot see how much space each card actually has. To choose between the tools, ask whether the answer is the same for the whole page (for example, a user preference or the page shell layout), which calls for a media query, or whether it depends on how much space the component was given, which calls for a container query.
Exercise
List three workarounds for components that need to adapt to their placement without container queries, and give one drawback of each.
Show answer
Possible answers: (1) Context-specific selectors such as aside .card tie the component to its location, so it is no longer reusable without new CSS. (2) Modifier classes such as .card--compact must be applied by hand and updated whenever the layout changes. (3) A ResizeObserver script that toggles a class works accurately but needs JavaScript, runs after layout, and may cause a flash or an extra layout pass. Intrinsic layout (flex-wrap, auto-fit grids) is another valid answer, with the drawback that it cannot express every conditional change.