Container size queries
Definition and purpose
Container queries adapt a component to the size of an ancestor rather than the viewport. Two copies on the same page can therefore use different layouts.
Narrow wrapper
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a, #b { background: lightblue; } #p { width: 180px; container-type: inline-size; } #a { padding: 4px; } @container (inline-size >= 240px) { #a { padding: 16px; } } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> </div> </body></html>The card retains its compact padding at both viewport widths.
Syntax and mental model
Set container-type: inline-size on a wrapper whose inline size is determined externally. Optionally assign container-name: card. Then @container card (inline-size >= 240px) styles descendants of that wrapper. The target cannot query its own size as its own container.
Wide named wrapper
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a, #b { background: lightblue; } #p { width: 300px; container: card / inline-size; } #a { padding: 4px; } @container card (inline-size >= 240px) { #a { padding: 16px; } } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> </div> </body></html>The named container meets the threshold independently of viewport size.
Common mistakes
Do not set size containment on an intrinsically sized element and expect its children to determine that size. Provide a usable base layout when no eligible ancestor exists.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Responsive media and safe areas. Next lesson: Container styles and scroll-state queries.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Container size queries — knowledge check
Five questions on container size queries.
What does a size query measure?
Which type enables inline-size queries?
Why name a container?
What if no eligible ancestor exists?
Can cards at the same viewport have different query results?