Before this lesson

Understand Grid, media queries and container sizing. Use a modern browser supporting container queries.

What you will be able to do

Adapt one component to narrow sidebars and wide content regions independently of viewport width.

Understand the mechanism

Viewport queries cannot distinguish a narrow sidebar from a wide main region within the same desktop window. Container queries let the component respond to its actual allocated space.

Establish inline-size containment on a wrapper and query it when styling descendants. Separate external size allocation from internal layout to avoid circular sizing assumptions. Named containers clarify nested cases.

Start with a complete narrow layout and enhance it when space permits. This also provides readable fallback behavior. Choose the threshold from actual content requirements, including controls and longer translations.

Learn basic size queries before more advanced units and features. Containment affects sizing and should not be applied indiscriminately. Test two instances at different widths on the same screen.

Runnable example

Run HTML examples as separate .html files in a modern browser. Prepare resource files and multi-file modules as described in the lesson.

<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Honeysuck practice</title></head><body>
<style>
.wrapper{container:course / inline-size;width:100%;margin:16px 0}
.card{display:grid;gap:16px;padding:20px;border:1px solid #b8cdbd;border-radius:12px}
.card .badge{background:#edf4e9;padding:20px;font-weight:bold}
@container course (min-width:500px){.card{grid-template-columns:120px minmax(0,1fr);align-items:center}}
.narrow{max-width:300px}.wide{max-width:760px}
</style><div class="wrapper narrow"><article class="card"><div class="badge">HTML</div><div><h2>Semantic content</h2><p>A narrow instance stays stacked.</p></div></article></div>
<div class="wrapper wide"><article class="card"><div class="badge">HTML</div><div><h2>Semantic content</h2><p>A wider instance can use two columns.</p></div></article></div>
</body></html>

Trace and verify

On a wide screen, narrow and wide instances should differ. At a 400-pixel viewport both stack. Keep the viewport wide but place the wide instance inside a 300-pixel parent and verify it stacks too.

Common mistakes and boundaries

A container still needs an understandable externally allocated size. Do not expect a descendant query to make the queried element size itself based on its own condition.

Practice challenge

Add an action that spans the narrow card and sits alongside content in a wide container. Test long Chinese and English titles.

Reference solution and reasoning

Keep the narrow default and change tracks or areas within the query. Allow the text column to shrink and wrap rather than fixing heading heights.

Further reading