This site uses third-party cookies, learn more or accept
dark light

CSS units of mesaurement

Written by Max Pelic on

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.

1body{

2 width:100vh;
3 min-height:100vh:
4}

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:

1.contain{

2 width:100vmin;
3 height:100vmin;
4}
5.cover{
6 width:100vmax;
7 height:100vmax;
8}

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

Share this article:

Previous Article: Password Generator #2

Next Article: Password show/hide animation