% vs vw vs vh in CSS — responsive layout units in practice
Relative units in CSS such as %, vw, and vh
are the foundation for responsive interfaces that work well across screens.
Lesson focus
This chapter focuses on layout units tied to the parent or the viewport, not typography units like rem.
If you are searching for the difference between % , vw, and vh or when to use relative units in CSS or best units for responsive design, this lesson explains it clearly.
What do relative units mean in CSS?
These units do not rely on a fixed value like px,
but on context such as the parent size or the viewport dimensions.
Simple definition: relative units adapt automatically to their environment, which makes them ideal for responsive design.
Using % in CSS
.container {
width: 100%;
}
.box {
width: 70%;
}
What does this code do? Makes the child width depend on the parent container width.
Expected result: a flexible width that changes as the parent changes.
Common mistake: assuming % always refers to the viewport.
Using vw in CSS
vw stands for Viewport Width, meaning a percentage of the screen width.
100vw= full screen width.50vw= half the screen width.
.banner {
width: 60vw;
}
What does this code do? Ties the element width directly to the viewport width.
Expected result: the element expands or shrinks directly with the screen.
Common mistake: using 100vw without considering the scrollbar in some cases.
Using vh in CSS
vh stands for Viewport Height, meaning a percentage of the screen height.
.hero {
height: 60vh;
}
What does this code do? Makes the element height depend on the viewport height.
Expected result: ideal for hero sections or large panels.
Common mistake: using 100vh on mobile without testing the browser UI.
When should I use % , vw, and vh in CSS?
- Use
%when you want the element to follow its parent size. - Use
vwwhen you want the element to follow the screen width directly. - Use
vhwhen you want height tied to the viewport, like hero sections.
rem for text, and %/vw/vh for layout.
Common Mistakes with CSS Relative Units
1) Using vh without mobile testing: can cause unexpected cropping or gaps.
2) Mixing units without a system: leads to inconsistent UI.
3) Ignoring parent context for %: creates unexpected layout results.
FAQ - Common Search Questions
What are relative units in CSS?
Units that depend on context like parent size or viewport dimensions, such as %, vw, and vh.
What is the difference between % and vw in CSS?
% usually depends on the parent element, while vw depends directly on the viewport width.
When should I use vh in CSS?
When you want height linked to the viewport, especially for hero sections.
Are vw and vh always good on mobile?
They are useful, but you should test because mobile browser UI can change height while scrolling.
What is the best practice for relative units?
Use a clear system: rem for text, and %/vw/vh for layout.