Viewport Units

What is a viewport?

The viewport is the visible area of a web page. It changes depending on the user’s device. It’s usually much smaller on mobile devices.

Before smartphones and tablets, web pages were only designed for computer screens, and it was common for them to have a fixed size.

Now, we often use smartphones and tablets to browse the internet, so fixed-size web pages are far too large to fit on these smaller screens. Flexible layouts are the solution to this!

CSS viewport units are a great way to get started with flexible layouts, which we’ll look at in detail in this lesson.

Viewport units

The vw unit

The viewport width (vw) unit represents a percentage of the user’s viewport width:

.element {
  width: 20vw;
}

So, 20vw is equal to 20% of the viewport’s width.

It’s similar to percentage, but the value remains consistent regardless of the value held by the parent elements. This is similar to how rem units remain relative to the root.

These vw units are often used for sizing responsive types, which is the type that adjusts its size based on the user’s screen size.

The vh unit

The viewport height unit represents a percentage of the user’s viewport height. So, 20vh equals 20% of the height of the viewport:

.element {
  width: 20vh;
}

This is the same as vw, but it’s based on height instead.

The vmin unit

The viewport minimum (vmin) unit is the minimum value between the height or width as a percentage. This value is whichever is currently smaller, vw or vh. So, 10vmin is 10% of the current width or height, depending on which one is smaller.

.element {
  width: 10vmin;
}

The vmax unit

The viewport maximum (vmax) unit is the maximum value between the height or width, and it’s given as a percentage. It’s the opposite of vmin, and is whichever value is currently larger, vw or vh. So, 20vmax is 20%\% of the set width or height (whichever is larger):

.element {
  width: 20vmax;
}

Which unit should you use?#

You can determine the most appropriate CSS unit by answering the following questions:

  • Do you want this element to scale when the viewport size changes?
  • If yes, what do you want it to scale relative to?

When you’ve answered these questions, determining the most appropriate unit is much simpler!

Example

Get hands-on with 1400+ tech skills courses.