vw and vh
Learn viewport units.
What is the viewport?
The viewport is the visible area of the browser window. CSS offers vw and vh units to measure it.
1vw is one percent of the viewport width, 1vh one percent of the height. As the window shrinks, the values shrink too, which makes them ideal for full-screen sections.
The vh unit
vh ties to the viewport height. For a .hero section, height: 100vh makes it fill the entire window height.
On mobile browsers the address bar can change the height, so dvh (dynamic viewport height) is sometimes preferred; for basic use, vh is enough.
vw vs %
vw ties to the viewport, % to the parent. For a .box, width: 50% is half the parent, width: 50vw is half the window.
When the parent shrinks, % shrinks too, but vw keeps following the window. This difference decides whether the layout tracks the screen or the container.
Exercise vw and vh for a hero section
Write a .hero selector. Set its width to 100vw and its height to 80vh.
Show example solution
/* add the hero section */
.hero {
width: 100vw;
height: 80vh;
}
Test yourself
-
What does 1vw mean?
/* vw ties to the window width */- One percent of the viewport width
- One percent of the parent's font size
- One pixel
- One percent of the root font size
Show answer
One percent of the viewport width — Correct. 1vw is one percent of the viewport width.
-
Full-screen height
.hero { height: ____vh; }Show answer
.hero { height: 100vh; } -
Match each unit to its meaning
- vw
- Viewport width
- vh
- Viewport height
- %
- Parent width
- rem
- Root font size