I’ve seen a lot of developers (especially novices) and other people who deal with CSS who do not really know the difference between units in CSS. And that’s kind of understandable — there are so many of them, one can get easily confused.
Let me shine some light on this topic. In this article, I’ll talk about three types of CSS units: Absolute, Relative and Viewport.
Absolute
As their name suggests, these units are of fixed size. They do not change according to screen size or anything else. After all, a centimeter is always a centimeter, right? These include
- cm — centimeters
- mm — millimeters
- in — inches
- pt — points
- px — pixels
- pc — pica
1 in = 2.54 cm = 254 mm = 72 pt = 96 px = 6 pc
Relative
This is where it gets a bit more complicated… In most browsers, the default font size is 16px — I suggest using this value as a basis for any relative calculations. Relative units are comprised of
- % — percentage
- em — font size of the element , relative to its parent(3em means that 3 times the normal font size)
- rem — font size of the element, relative to the root html element
- ch — width of the “0” character (in monospace fonts all characters are of equal width)
- ex —x-height of the font used (the height of “x” character)
Note, that ch and ex will change with the font you are using.
Viewport Units
Viewport units are relative in their nature as well, though they are different from Relative Units. As the name suggests, they are relative to your browser’s viewport size. They include:
- vw — % of viewport width
- vh — % of viewport height
- vmin — % of the smaller dimension (width or height)
- xmax — % of the larger dimension (width or height)
Well, that’s it for now. I hope you have a better understanding of how different CSS units work and when to use them.
Of course, there are also angles like deg and rad, time (s and ms) and even frequency (Hz and kHz), but those are not used very often…
Have a nice day!
Bradley Nice, Content Manager at ClickHelp.com — best online documentation tool for SaaS vendors
Written by