0
0
CssConceptBeginner · 3 min read

When to Use vw and vh Units in CSS: Practical Guide

Use vw and vh in CSS to size elements relative to the browser's viewport width and height. They are perfect for creating layouts that adapt smoothly to different screen sizes without fixed pixel values.
⚙️

How It Works

Imagine the browser window as a rectangle you can resize. The vw unit means "viewport width" and represents 1% of that window's width. Similarly, vh means "viewport height" and equals 1% of the window's height.

So if you set an element's width to 50vw, it will always be half the width of the visible browser area, no matter the device or screen size. This is like using a ruler that changes length depending on the window size, making your design flexible and responsive.

💻

Example

This example shows a box sized using vw and vh units. It will always fill half the viewport width and 30% of the viewport height.

css
html, body {
  margin: 0;
  height: 100%;
}
.box {
  width: 50vw;
  height: 30vh;
  background-color: #4CAF50;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  border-radius: 8px;
  margin: 20px auto;
}
Output
A green rectangular box centered horizontally, half the browser width and 30% of the browser height, with white text inside.
🎯

When to Use

Use vw and vh when you want elements to scale with the browser size. This is great for:

  • Full-screen sections or hero banners that fill the viewport.
  • Responsive typography that adjusts with screen width.
  • Layouts that need consistent proportions on different devices.
  • Creating elements that maintain size relative to the visible screen, regardless of device orientation.

Avoid using them for very small UI elements where precise control is needed, or inside containers that scroll independently from the viewport.

Key Points

  • vw is 1% of the viewport width.
  • vh is 1% of the viewport height.
  • They help create flexible, responsive designs without fixed pixels.
  • Great for full-screen layouts and scaling elements with screen size.
  • Not ideal for elements inside scrollable containers or needing fixed sizes.

Key Takeaways

Use vw and vh to size elements relative to the browser window for responsive design.
vw equals 1% of viewport width; vh equals 1% of viewport height.
Ideal for full-screen sections, responsive typography, and flexible layouts.
Avoid vw/vh for small UI parts needing precise fixed sizes.
They adapt automatically when the user resizes the browser or changes device orientation.