CSS Viewport Units

CSS Viewport Units

Pixels, EM, REM, Percent.  These units of web design have been around for ages, but there’s another that hasn’t gotten much attention until now.  Viewport Units have been around for a few years, but they’ve only recently seen adoption by all major browsers and they’re quickly transforming the foundation of responsive web design.

A Quick Into

The “viewport” is the area of your browser where the content lives.  That area in the browser without the toolbars, buttons, etc.  The CSS units are vw, vh, vmin and vmax and they all represent a percentage of that usable area of the browser, the viewport.

Let’s say our browser is arbitrarily 1000px wide and 800px high:

  • vw: 1% of the viewport’s width.  In this case, 50vw = 500px wide (50%); 100vw = 1000px wide (100%)
  • vh: 1% of the viewport’s height. So, 50vh = 400px high (50%); 100vh = 800px high.
  • vmin: a percentage of the height or width (whichever is smaller). 50vmin is half of the smallest dimension (800px), so it’s 400px in our example.
  • vmax: a percentage of the height or width (whichever is larger). So 50vmax = 500 because it’s half the width of 1000 (the bigger number).

vmax and vmin are perhaps the most interesting (and confusing) viewport units, but think about tablet and mobile devices that quickly and often switch between landscape and portrait modes.

Take Up the Full Height of the Page

If you’ve ever tried to create a cover page where the background image is the full height of the browser viewport, you’ve probably struggled with percentages.

#full-height{ height: 100%; }

But this doesn’t always work unless you also set the height of the BODY and HTML tags to 100% height as well and that often breaks the rest of the design.

Consider, instead, using viewport units like so:

#full-height{ height: 100vh; }

This works perfect for that full screen hero image you always wanted.

Use for Responsive Font Sizing

So that’s all fine and good, but viewport units are just getting warmed up.  You can also use them to set the font size without using a ridiculous number of media queries.  For example:

h2.text-responsive{ font-size: 6vw; }
h4.text-responsive{ font-size: 3vw; }

Very cool.

Responsive Vertical Centering

If you set an element’s width, height and margins in viewport units, you can center it without using any hacks/tricks.  Let’s say we have a rectangle with a height of 60vh and top and bottom margins of 20vh (which adds up to 100vh; 60 + 2 * 2).  This rectangle will remain centered, even on window resize.

#element { width: 60vw; height: 60vh; margin: 20vh auto;}

</huge CSS>

Viewport units are almost certainly going to take the place of percentages as responsive web design continues its rise in popularity.  There’s a little bit of a learning curve, but it’s well worth your time to experiment.  Your stylesheets will thank you.

Leave a Reply