Viewport-Based CSS Measurements

I wish I knew how to use viewport-based measurements before!

Let’s kick the series off with a quick one.

When I was starting out with my development career, I only knew how to use pixels and percentages. It was back in the day when the word “responsive” wasn’t yet a buzzword, and making something respond perfectly to the viewports’ dimensions was impossible without JavaScript.

Fast-forward to 2010, CSS3 came along and it introduced a lot of new features including viewport-based measurement units. That’s what we’re looking at today.

The Units

  • vw: represents 1% of the viewport’s width
  • vh: represents 1% of the viewport’s height

One important thing to remember is that these units will ALWAYS be relative to the viewport. The only exception here is if you’re using it inside an iframe (since they are sort of separate windows on their own).

Let’s See it in Action

In this first example, we’ll try to create our own pop-up modal. The goal is to make it so that the modal’s width is always 80% of the viewport’s width, its height always 60% of the viewport’s height, and always at the center of the page.

Simple modal implementation

The use of vw and vh above were pretty straight-forward. But some of you might be saying “But I can also achieve this using %, why use vh and vw?”

Let’s look at another example. Suppose we’re creating a site/app similar to the Clear app, and we want it to always be able to accommodate 4 items in the screen, and clicking on an item will make it expand to cover the whole viewport. How do we do it?

How easy was that? Using vh, we were able to meet all the requirements without lengthy % calculations, and without using JavaScript to determine the height of the viewport.

Combining it with calc()

You can also achieve great results by combining these units with the CSScalc function. It can look something like this:

.modal-body {
max-width: 800px;
width: calc(100vw - 80px);
margin: 0 auto;
}

This will force the .modal-body to always be 80px less than the viewport’s width (hence giving it a 40px horizontal space on both sides), but ensure that it’ll never go pass 800px.

There’s still a lot you can do with these, but I’ll leave it up to your creativity and imagination. I hope this helped!

Browser Support

  • IE 10+
  • Firefox 19+
  • Chrome 34+
  • Safari 7+
  • Android 4.4+
  • iOS 6+

For more info, you can read the full documentation in Can I Use.

Like what you read? Give Joshua Cerbito a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.