CSS units in a nutshell.
In this post, I will explain the most used CSS units that you will use if you are a frontend developer.
There are a lot of CSS units but we can make it simple by dividing them into two categories:-
1. Absolute units
2. Relative units
These units are fixed and anything that is expressed using these units will appear the same.
For eg:- Suppose you define the width and height of an image at 450px × 450px.
So no matter whichever device whether it may be a phone, tablet or PC. It will be the same size (excluding the use of media queries).
Examples of absolute units:- px (pixel), in (inches), pt (points), cm (centimeters), mm(millimeters)
px (pixel) is by far the most used absolute length unit.
Units that are relative to something, which means opposite to absolute, relative units can change the size of elements.
For eg:- If you define a border of 1em on an image if a user zoom in then the border size will change.
Many people find it hard to understand relative units so I will try to explain them to the best of my ability. But first, you should know the different types of relative units.
em, rem, vw, vh, % and many more but these are the most widely used.
Relative units are relative to something, it can be font size or viewport height.
If you use ‘em’ it is relative to the font size of the element (2em means 2 times the size of the current font)
If you use ‘rem’ it is relative to the font size of the root element (which is most probably always set to 16px). Root means browser default font size or the font size that you have set for the entire document.
‘vh’ means viewport height and ‘vw’ means viewport width, by the name they are relative to the viewport, % also refers to the viewport.
I hope this post helped you understand the CSS units in a better way.
Thank you for reading till the end.