Viewport and container units overview
Definition and purpose
Viewport-relative units describe a fraction of the viewport, while container query units use an eligible ancestor query container. They make sizing responsive to different contexts without choosing a single fixed width.
Viewport fractions
<!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>#a { width: 20vw; height: 10vh; }</style> </head> <body> <div id="a">Viewport</div> </body></html>At 375px viewport width this is 75px; at 1280px it is 256px. Both test viewports are 800px tall, so height is 80px.
Syntax and mental model
1vw is one percent of viewport width and 1vh of viewport height; small, large and dynamic viewport variants account for changing browser UI. In horizontal writing, container-type: inline-size establishes an inline-size query container, so descendants can use cqi. Without an eligible container, that unit falls back to the small viewport inline unit. Full container queries come later.
Container-relative size
<!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> .panel { width: 240px; container-type: inline-size; } #a { width: 50cqi; } </style> </head> <body> <div class="panel"> <div id="a">Card</div> </div> </body></html>The card uses half the panel inline size, not half the viewport.
Common mistakes
Avoid using 100vw as a universal substitute for width: 100%; scrollbar and parent sizing can differ. A viewport unit alone is not a reliable accessible font-size strategy. Test actual mobile UI changes separately.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Percentages and reference sizes. Next lesson: Math for flexible sizes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Viewport and container units overview — knowledge check
Five questions on viewport and container units overview.
What is 20vw in a 500px viewport?
Which unit follows dynamic viewport height?
What does cqi measure?
No eligible inline-size container: what is the cqi fallback?
Why use cqi for a card in different sidebars?