CSS units of mesaurement
In CSS, there are lots of units of measurement you can use to change the size of text, elements, and other style properties. In this post, I’ll go over a few of the less common ones and how they can be used.
View Width / View Height
One unit of measurement is a vw
or vh
. A vw
is one percent of the width of the browser (called the viewport), and a vh
is one percent of the viewport’s height. For example, if the viewport was 500 pixels
wide, 1vw
would be 5 pixels
, and 5vw
would be 25 pixels
.
If you want to make your webpage cover the whole screen, one method of doing this is using vw
and vh
.
body{
width:100vh;
min-height:100vh:
}
VMIN and VMAX
vmin
and vmax
work similarly to vw
and vh
. vmin
is one-hundredth of the smallest dimension of the viewport, and vmax
is one-hundredth of the largest dimension of the viewport.
These can be useful if you want to keep a box smaller than the size of the viewport, or you want to cover the viewport with an element while keeping it square. For example:
.contain{
width:100vmin;
height:100vmin;
}
.cover{
width:100vmax;
height:100vmax;
}
Caracter width and height
Similar to the em
unit, which is based on the font size, ch
and ex
are based on the size of the characters in a font. ch
is equal to the width of the 0
character and ex
represents the x-height of the font (height of a lowercase character).
Some things to note
All these units work beautifully with the CSS calc
function, which can be used to perform calculations to combine different units. For example, if you want to make an element 30px skinnier than the viewport, you could use calc(100vw - 30px)
You can view a full list of units and their support at quirksmode.org