Volkswagen logo

Este artículo también está disponible en español

Some properties and values don’t gain a lot of developer attention, either because a particular spec is not "sexy" enough or because use-cases don’t seem immediately obvious. Good examples of the latter include the vw, vh, vmax and vmin length measurements, which have been part of the CSS3 Values & Units Module for some time but are just now finding support in modern browsers.

As we’ll see in the next article, these new measuring systems are natural fits for creating adaptive and responsive site designs; for now, let’s take at the general idea of the new units.

Why Do We Need Another Way Of Measuring Things In CSS?

The principles behind vw, vh are simple: they represent percentages of the browser viewport’s width and height, respectively.

1vw = 1/100 of the current viewport width, i.e. 1% of the width

15vh = 15/100 of the viewport’s current height or 15% of the height

Both vw and vh can take any positive number: integers and floating point values are all valid.

At first glance, vw and vh would appear to be somewhat redundant, as we already have a measuring system that relates to the viewport width as a percentage. For example:

div { width: 50%; }

Applied to almost any element, a percentage width correlates the size of an element to the size of its container, which may include the browser window: indeed, the concept and practice of fluid images relies entirely on this fact. But a little consideration shows that percentage measurements have some significant limitations:

  1. body width does not include the margin
  2. viewport height has always been difficult to measure, as the height of the <body> depends on the amount of content on the page, not the dimensions of the browser window.
  3. Most importantly, percentage width of the body cannot be applied to the size of text. font-size: 15% sizes the font relative to its native or natural proportions, not the dimensions of the viewport.

So the equivalent in vw units to the declaration above (ignoring any margin that may have influenced the <div>) would be:

div { width: 50vw; }

To scale a heading in relation to the width of the browser window, you could use:

h1 { font-size: 5vw; }

Conclusion

The vw and vh units have unique application to mobile development, and offer the only way to predictably scale text in response to viewport size, while supplying a useful way to make perfect responsive shapes.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.