Translate

Tuesday, 9 June 2020

CSS Viewport Units: A Quick Start

CSS Viewport Units

It’s been a few years since viewport units were first introduced in CSS. They’re truly “responsive length units” in the sense that their value changes every time the browser resizes. If you’ve heard about these units before but never learned about them in detail, this article can help you out.

The Units and Their Meaning

There are four viewport-based units in CSS. These are vh, vw, vmin and vmax.

  • Viewport Height (vh). This unit is based on the height of the viewport. A value of 1vh is equal to 1% of the viewport height.
  • Viewport Width (vw). This unit is based on the width of the viewport. A value of 1vw is equal to 1% of the viewport width.
  • Viewport Minimum (vmin). This unit is based on the smaller dimension of the viewport. If the viewport height is smaller than the width, the value of 1vmin will be equal to 1% of the viewport height. Similarly, if the viewport width is smaller than the height, the value of 1vmin will be equal to 1% of the viewport width.
  • Viewport Maximum (vmax). This unit is based on the larger dimension of the viewport. If the viewport height is larger than the width, the value of 1vmax will be equal to 1% of viewport height. Similarly, if the viewport width is larger than the height, the value of 1vmax will be equal to 1% of hte viewport width.

Let’s see what the value of these units will be in different situations:

  • If the viewport is 1200px wide and 1000px high, the value of 10vw will be 120px and the value of 10vh will be 100px. Since the width of the viewport is greater than its height, the value of 10vmax will be 120px and the value of 10vmin will be 100px.
  • If the device is now rotated so that the viewport becomes 1000px wide and 1200px high, the value of 10vh will be 120px and the value of 10vw will be 100px. Interestingly, the value of 10vmax will still be 120px because it will now be determined based on the height of the viewport. Similarly, the value of 10vmin will still be 100px.
  • If you resize the browser window so that the viewport becomes 1000px wide and 800px high, the value of 10vh will become 80px and the value of 10vw will become 100px. Similarly, the value of 10vmax will become 100px and the value of 10vmin will become 80px.

At this point, viewport units may sound similar to percentages. However, they’re very different. In the case of percentages, the width or height of the child element is determined with respect to its parent. Here’s an example:

See the Pen Viewport Units and Percentage by SitePoint (@SitePoint) on CodePen.

As you can see, the width of the first child element is set to be equal to 80% of its parent’s width. However, the second child element has a width of 80vw, which makes it wider than its parent.

Continue reading CSS Viewport Units: A Quick Start on SitePoint.



No comments:

Post a Comment