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
1vhis equal to 1% of the viewport height. - Viewport Width (vw). This unit is based on the width of the viewport. A value of
1vwis 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
1vminwill be equal to 1% of the viewport height. Similarly, if the viewport width is smaller than the height, the value of1vminwill 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
1vmaxwill be equal to 1% of viewport height. Similarly, if the viewport width is larger than the height, the value of1vmaxwill 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
10vwwill be 120px and the value of10vhwill be 100px. Since the width of the viewport is greater than its height, the value of10vmaxwill be 120px and the value of10vminwill be 100px. - If the device is now rotated so that the viewport becomes 1000px wide and 1200px high, the value of
10vhwill be 120px and the value of10vwwill be 100px. Interestingly, the value of10vmaxwill still be 120px because it will now be determined based on the height of the viewport. Similarly, the value of10vminwill still be 100px. - If you resize the browser window so that the viewport becomes 1000px wide and 800px high, the value of
10vhwill become 80px and the value of10vwwill become 100px. Similarly, the value of10vmaxwill become 100px and the value of10vminwill 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