Demystifying CSS units

Akash Verma
3 min readMar 18, 2019

--

We use units in our daily life to express the values, kilograms or pounds for measuring the mass of an object , inches to measure length and seconds to measure time. Units in CSS are the same thing , if you have had a bad experience with them you may think they are more complex , illogical , but once you think of them the way it is interpreted things start to get clear.

In this post, I’d like to talk about a couple of CSS units (px, rem, % & em). How they are computed during run-time in the browser context.

It is important to note that each time we use a unit other than px it ultimately gets converted before being rendered in the browser.

How CSS values are processed?

Stages of CSS parsing

Let us break down how CSS values are processed in different stages.

  • Declared value: Authors (developers) defined values in the CSS files.
  • Cascaded value: Multiple style-sheets can affect the styling of an element. This represents the winning value over others following specificity rules.
  • Specified value: Each property of an element needs to be computed before being painted in the browser, this represents the default value applied by browser if un-declared by the author of the page.
  • Computed value: Represents the absolute conversion of all the relative values.
  • Used Value: Represents final computed value based on layout.
  • Actual value: Represents actual value taken into account while rendering in the browser. For e.g. — A width of 184.8 px is converted to 185 px because of browser’s limitation to take into account decimal values while painting the element.

How units are converted from Relative to Absolute?

Let’s assume the author defined value is x units . The absolute value is converted as follows in different scenarios:

  • %(fonts): The absolute font-size value is x% of the parent’s computed font-size.
  • %(lengths): The absolute length value (width or height) is x% of the parent’s computed width.
  • em (font): The absolute font-size value is x * parent’s computed font-size.
  • em (lengths): The absolute length value (width or height) is x * current element’s computed font-size.
  • rem: The absolute value (length or font) is x * root computed font-size. The default root font-size is 16 px.
  • vh: The absolute value is x * 1% of the current viewport height.
  • vw: The absolute value is x * 1% of the current viewport width.
Relative units to absolute conversion chart

The conversion chart gives you a clear picture while deciding on how the CSS units are interpreted.

If you liked reading this, don’t forget to clap. 👏👏

You can also follow me on twitter @Akash940 for JavaScript or React updates.

Thank-you!

--

--

Akash Verma

JavaScript Enthusiast, Software Engineer @goevive. Follow me on twitter @Akash940