Viewport Percentage Units

When we describe the viewport we are talking about the visible area of the website at the current time. Viewport units are relative to the viewport. This makes them incredibly useful for sizing fonts relative to the size of the viewport the user has without needing to use media queries.

The CSS Layout Workshop: Viewport units

Viewport units can also be used for certain layout tasks, as I’ve outlined briefly here and we’ll see more use cases in the rest of the course.

vh: 1/100th of the height of the viewport

This unit makes it easy for us to make an element as tall as the viewport. For example a full screen hero image.

<div class="hero">

</div>

<div class="content">
  <p>This content should be below the 'fold'.</p>
</div>
.hero {

  background-image: url(my-image.jpg);
  background-size: cover;
  height: 100vh;
  width: 100%;
}

vw: 1/100th of the width of the viewport

You can use the vw unit for simple, flexible grids. The example below demonstrates two columns, one of 30vw and one of 60vw floated left and right.

<div class="col1">
  This column takes up 30vw. 
</div>

<div class="col2">
  This column takes up 60vw.
</div>
.col1 {
  box-sizing: border-box;
  padding: 1em;
  width: 30vw;
  float:left;
  border: 4px solid #ccc;
}

.col2 {
  box-sizing: border-box;
  padding: 1em;
  width: 60vw;
  float: right;
  border: 4px solid #ccc;
}

This isn’t a bulletproof method for creating a flexible grid, and is best reserved for creating ‘hero’ areas of your design where images and typography need to scale according to the viewport. Some additional resources can be found at:

vmin: equal to the smaller of vh or vw

A value of 10vmin would be equal to 10vh if the viewport was shorter than it is wide, and 10vw if the viewport is taller than it is wide.

vmax: equal to the larger of vh or vw

A value of 10vmax would be equal to 10vh if the viewport was taller than it is wide, and 10vw if it is shorter than it is wide.

Browser compatibility

These newer units were defined in level 3 of the CSS Values and Units Module, therefore are unsupported by some older browsers. In IE9 and up you can use vh and vw, IE9 uses vm instead of vmin and at the time of writing no IE or Edge browser supports vmax.