Using Viewport Units in CSS: vw and vh

Hero image for Using Viewport Units in CSS: vw and vh. Image by Ilyuza Mingazova.
Hero image for 'Using Viewport Units in CSS: vw and vh.' Image by Ilyuza Mingazova.

CSS viewport units are units of measurement that are based on the size of the viewport or the visible area of a web page and can be especially useful for responsive web development as they allow us to create interfaces that automatically adjust to the size of the screen on which they are being viewed.

The two most commonlyused viewport units are vw (viewport width) and vh (viewport height). These units are equivalent to 1% of the viewport's width and height respectively. So for example, if the viewport's width is 1000 pixels, then 1vw is equal to 10 pixels, and 50vw would be 500 pixels. Similarly, if the viewport's height is 800 pixels, then 1vh is equal to 8 pixels.

The important thing to bear in mind is that these are fluid, dynamic units, which means that as the screen size changes, so do the calculated values. If that 1000pxwide screen we talked about previously was resized to 500 pixels wide instead, then 1vw would become 5px, and 50vw would become 250px.

They are entirely interchangeable with any other standard form of CSS unit and can simply be included in your property values, like so:

.example {  width: 50vw;  height: 25vh;}

This would set the width of the element .example to 50% of the viewport's width, and the height to 25% of the viewport's height (assuming of course that it is a blocklevel element).

Support is already reasonably good, but you should still consider offering a fallback value for any older browsers that might visit your application, either using percentage units (which may be equivalent depending on the contextual layout of your element), or otherwise explicit units.

So, revisiting the example above:

.example {  width: 200px;  width: 50vw;  height: 150px;  height: 25vh;}

This would fall back to an element 200px wide and 150px high on nonsupporting browsers.

Overall, viewport units provide a powerful tool for responsive web development, allowing developers to create interfaces that automatically adjust to the size of the screen on which they are being viewed. However as with any relatively new CSS featured it is important to be aware of their limitations and to test your developments carefully to ensure that they work as expected across the matrix of devices and browsers you support.


Categories:

  1. CSS
  2. Front‑End Development
  3. Responsive Development
  4. Sass