0
0
CSSmarkup~5 mins

Viewport units in CSS

Choose your learning style9 modes available
Introduction

Viewport units help you size elements based on the visible area of the browser window. This makes your design adjust smoothly when the window size changes.

To make text or images scale with the browser size for better readability.
To create full-screen sections that always fill the entire browser window.
To set margins or padding relative to the screen size for consistent spacing.
To build responsive layouts that adapt to different devices without fixed pixel sizes.
Syntax
CSS
width: 50vw;
height: 100vh;
font-size: 5vmin;

vw means 1% of the viewport's width.

vh means 1% of the viewport's height.

vmin is the smaller value between vw and vh.

vmax is the larger value between vw and vh.

Examples
This makes the div fill the entire browser window width and height.
CSS
div {
  width: 100vw;
  height: 100vh;
}
The paragraph text size adjusts based on the smaller side of the viewport, keeping it readable on all devices.
CSS
p {
  font-size: 3vmin;
}
The header has vertical padding based on viewport height and horizontal padding based on viewport width.
CSS
header {
  padding: 5vh 10vw;
}
Sample Program

This example shows a blue box that fills the whole browser window. The text inside scales with the viewport size using vmin. When you resize the browser, the box and text adjust smoothly.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Viewport Units Example</title>
  <style>
    body, html {
      margin: 0;
      height: 100%;
    }
    .full-screen {
      width: 100vw;
      height: 100vh;
      background-color: #4a90e2;
      display: flex;
      justify-content: center;
      align-items: center;
      color: white;
      font-size: 5vmin;
      text-align: center;
      padding: 2vmin;
    }
  </style>
</head>
<body>
  <div class="full-screen">
    <p>This box fills the entire browser window.<br>Resize the window to see the text and box adjust.</p>
  </div>
</body>
</html>
OutputSuccess
Important Notes

Viewport units are great for responsive design but be careful on mobile browsers where the viewport height can change when the address bar shows or hides.

Use vmin and vmax to keep sizes balanced between width and height.

Summary

Viewport units let you size elements relative to the browser window size.

Use vw, vh, vmin, and vmax for flexible, responsive layouts.

They help your design look good on all screen sizes without fixed pixels.