📜 ⬆️ ⬇️

Sizing with vw and vh units

In CSS3, new units of measurement. ( I, apparently, already spoke about it. Eng ) You already heard about px, pt, em and new rem. Let's look at a few more: vw and vh.

Often there are elements in the layout that are guaranteed to fit into the browser's viewport. In general, JavaScript is used for this. Check the size of the viewport and resize the elements accordingly. If the user resizes the browser window, the procedure is repeated.

With vw / vh we can set the size of the elements relative to the size of the viewport. The units vw / vh are interesting in that 1vw is a unit equal to 1/100 of the viewport width. To assign an element a width equal to the width of the viewport, for example, you need to set the width: 100vw.
')

How can this be used


Lightboxes are an excellent candidate for using vw and vh, since they are usually positioned relative to the viewport, but it seems to me that it is easier to use position: fixed with the values ​​of top, bottom, left and right, since you can not set the height and width at all .

You can use new units of measure to set the sizes of elements that are in normal flow. For example, I can place on the page screenshots. The height of these screenshots should not exceed the height of the viewport. For this, I can set the maximum height of the images:

img { max-height:95vh; }

In this case, I set the height to 95vh to leave some space around when they are on the screen.

Browser Support


If rem is supported by almost all major browsers including IE9, then using vw and vh is worth the wait. Currently only Internet Explorer 9 supports them.

Links


Spec eng

Units vm


On the advice of gd666 decided to add a little.
There is one more unit of measurement related to the viewport, which was not mentioned in the original article. This is vm.

vm is calculated relative to the width or height of the viewport, depending on which one is smaller. The smaller of the values ​​is 100 vm. When resizing the viewport, the dimensions specified in vm will change accordingly.

You can read about it in the specification. eng

Source: https://habr.com/ru/post/126863/


All Articles