0
0
CssHow-ToBeginner · 3 min read

How to Use Viewport Units in CSS: Simple Guide

Viewport units in CSS are vw, vh, vmin, and vmax, which represent percentages of the viewport's width and height. You use them by assigning these units to CSS properties like width, height, font-size, etc., to make elements scale with the browser window size.
📐

Syntax

Viewport units are used by adding vw, vh, vmin, or vmax after a number in CSS values.

  • vw: 1% of the viewport's width
  • vh: 1% of the viewport's height
  • vmin: 1% of the smaller side (width or height)
  • vmax: 1% of the larger side (width or height)
css
selector {
  property: valuevw;
  property: valuevh;
  property: valuevmin;
  property: valuevmax;
}
💻

Example

This example shows a box that is always 50% of the viewport width and 30% of the viewport height. The font size also scales with the viewport width.

css
html, body {
  margin: 0;
  height: 100%;
}
.box {
  width: 50vw;
  height: 30vh;
  background-color: #4CAF50;
  color: white;
  font-size: 5vw;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 1rem;
}
Output
A green rectangular box centered with white text that scales in size as the browser window changes.
⚠️

Common Pitfalls

Common mistakes include:

  • Using viewport units for very small text can make it unreadable on small screens.
  • Not combining viewport units with max-width or max-height can cause elements to become too large.
  • For mobile browsers, the viewport height can change when the address bar shows/hides, causing layout jumps.

Always test on different devices and consider combining viewport units with other units for better control.

css
/* Wrong: font size too small on small screens */
.text {
  font-size: 1vw;
}

/* Better: minimum font size with clamp() */
.text {
  font-size: clamp(1rem, 2vw, 3rem);
}
📊

Quick Reference

UnitMeaningExample Usage
vw1% of viewport widthwidth: 50vw;
vh1% of viewport heightheight: 30vh;
vmin1% of smaller viewport sidefont-size: 5vmin;
vmax1% of larger viewport sidemargin: 2vmax;

Key Takeaways

Viewport units let you size elements relative to the browser window size.
Use vw for width-based sizing and vh for height-based sizing.
Combine viewport units with other CSS functions like clamp() for better responsiveness.
Test viewport unit usage on different devices to avoid readability or layout issues.
Remember vmin and vmax depend on the smaller or larger viewport dimension.