Should I use Pixel, Rem, or Em?
Learn to differentiate the 3 size units px, rem, or em, and when to use which one.
Last updated
Learn to differentiate the 3 size units px, rem, or em, and when to use which one.
Last updated
If you're familiar with the web design world, you've probably heard of these units. The questions are what exactly are they and what units of measurement we should use in our CSS.
Pixel is an absolute and fixed-size unit in CSS. It is probably the most used unit in CSS and is very popular when it comes to settings the font-size of text on web pages.
One pixel (1px) is defined as 1/96th of an inch in print media.
Different devices have a different number of pixels per inch on their screens, this is known as pixel density. Although the size of a pixel isn't always the same, the font-size, margin, and padding in pixel (px) remain the same for all the screens.
Em is a relatively flexible and scalable unit of typography. Because CSS is cascading and inheritable, em will inherit font-size value from the parent element.
Rem (root em) stands for "root element's font-size". It is a relative unit of CSS and is translated by the browser to pixels (px).
Rem works almost the same as Em, but the main difference is that Rem only references the font-size of the root element on the page rather than the parents' font-size.
There is no perfect answer to this question.
Let's look at some examples of where to use these units.
On-point measurements of your content will dictate the look and feel of your website, however, you'll need to get creative.
Font size: Now px and rem basically have the same effect on the text; as we would get the same result if we used 32px and 2rem. This is because the default root font-size is 16px.
If you want to scale the element's size based on the root size, no matter what the parent size is, use rem.
Padding and margin: Because of the inheritable, em unit will be helpful for padding and margin. By using em, we can make the padding and margin scale proportionately.
Border width: both rem, em, and px can be used based on your use case. Most of cases, px is recommended since the value we give to the border width is so small that it is almost not noticeable if we change the root font-size.