Easy css sizing with vw and vh

A common task you may encounter while developing a web interface is creating an element that perfectly fit the browser’s space. usually you can do it with some percentages or via javascript, but CSS3 offers a better solution.

VH and VW sizes

By using those two units, we define the size of an element relative to the size of the viewport.

  • 1vh unit reflects 1/100 of the viewport’s height
  • 1vw unit reflects 1/100 of the viewport’s width

So, if we need a box that perfecly fill all the screen we can write:

<div style="width: 100vw; height: 100vh"> Hello World ! </div>

or if we need only the top half:

<div style="width: 100vw; height: 50vh"> Hello World ! </div>

Easy? 😉


In a similar way we can also use vmin and vmax:

  • 1vmin unit is 1/100 of the shortest side of the viewport
  • 1vmax unit is 1/100 of the longest side of the viewport

This way we can easily manage flippable viewports on mobile devices.

You can use those units just like any other px, em, pt, and so on, so you are free to use it on borders, margins, and also fonts, as this cool video by csstricks shows:


Csstricks article: https://css-tricks.com/viewport-sized-typography/

Browser compatibilty sheet:  http://caniuse.com/#feat=viewport-units