Trang Chủ

Learn about CSS Viewport Units

Introduce

It has been a few years since Viewport units were introduced in CSS. They are responsive units meaning their values ​​change every time the browser is resized. If you’ve heard of these units before but haven’t learned them in detail, this article can help you understand them better.

Units and their meanings

There are 4 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. The value of 1vh is 1% of the height of the viewport.
  • Viewport Width (vw) – This unit is based on the width of the viewport. The value of 1vw equal to 1% of the viewport width.
  • Minimum Viewport (vmin) – This unit is based on a smaller size of viewport. If the viewport height is less than the width, the value of 1vmin will equal 1% of the viewport height. Similarly, if the width of the viewport is less than the height, the value of 1vmin will be equal to 1% of the width of the viewport.
  • Viewport Maximum (vmax) – This unit is based on a larger viewport size. If the height of the viewport is greater than the width, the value of 1vmax will be equal to 1% of the height of the viewport. Similarly, if the width of the viewport is greater than the height, the value of 1vmax will be equal to 1% of the width of the viewport.

Let’s look at the values ​​of these units in different situations:

  • If the view is 1200px wide and 1000px high, the value of 10vw will be 120px and 10vh will be 100px. Because the viewport width is greater than the height of the viewport, the value of 10vmax will be 120px and 10vmin will be 100px.
  • If the device is in rotated mode, the viewport will be 100px wide and 1200px high, 10vh will be 120px and 10vw will be 100px. Interestingly, the value of 10vmax is still 120px because it will be calculated based on the height of the viewport. Similarly 10vmin would be 100px.

The viewport units seem similar to % units. However, they are very different. In the case of % , the width or height of a child element is defined for its parent. Here is an example:

 

Chia sẻ bài viết ngay