TL;DR — CSS units refer to values that properties accept. Properties take a wide range of value such as percentages: relative units that are flexible, and absolute units such as pixels that are always the same.
The use of CSS units
The majority of CSS properties accept specific values such as percentages, pixels, centimeters, or other units. Percentages calculate font-size,
width, or another property according to the parent element. Additionally, some elements do not need CSS units, just numbers (for instance, opacity).
Relative length units such as relative to other elements or settings. For instance, CSS em is relative to the font size of the parent element.
Such units are useful for making sure that sizes of certain elements scale with other components of a page. You can use relative units to control the height and
width as well.
|em||Relative to the parent element font-size (3em means 3 times the current font size)|
|ex||Relative to the current x-height of font (used rarely)|
|ch||Relative to the 0 width (zero)|
|rem||Relative to the root (html) element font-size|
|vw||Relative to the viewport* 1% width|
|vh||Relative to the viewport* 1% height|
|vmin||Relative to the 1% of viewport smaller dimension|
|vmax||Relative to the 1% of viewport bigger dimension|
Theory is great, but we recommend digging deeper!
Absolute CSS units refer to units that are always the same. They are not relative to other elements or components of a page.
|in||inches (2.54 cm = 96px = 1in)|
|px *||pixels (1/96th of 1in = 1px)|
|pt||points (1/72 of 1in = 1pt)|
|pc||picas (12 pt =1pc)|
Em vs Rem
The CSS em and rem are two relative units that you can use for sizing elements. The main difference between these two units is what they are relative to. em is relative to the font-size of its parent, and rem is relative to the root font-size.
Therefore, rem determines the pixel size according to the <html> element. The size of the element with rem multiplies by the number attached to the unit.
When turning CSS em to px value, the final size is multiplied by the font size of the parent element.
Note: the conversion from px to rem happens like this - 20px is 1.25rem (when root font size is 16px). When we turn the px to em unit, we can consider the parent element with 15px font size. Then, 20px would be 1.333em.