Niraj Chauhan

Niraj Chauhan

#father#husband#SoftwareCraftsman#foodie#gamer#onepiece#naruto

CSS: What's the difference between px, em & rem?

Most of us grew up using px CSS unit. This code should be familiar to you width: 100px;. But in the past few years, I saw other units getting added to the CSS specs. So let’s understand each of them.

Pixel(px)

So the word pixel doesn’t mean a single pixel of your screen. This was shocking for me as well but it’s true since 1996. Pixels are relative to the resolution of the canvas. By default, CSS defines the reference pixel which is usually a pixel on a 96 DPI display. Now we know that there are displays with different DPI like retina displays, in that case, the user agent rescales the pixel to match that of the display. So for retina displays, 1 CSS pixel is actually 2 Retina display pixels.

So with newer displays coming up, new CSS units had to be introduced.

em

Unlike pixels that are relative to displays, em’s are relative to the parent elements font-size. So for eg: parent elements font-size is 16px then the child elements 1em value is 16px. Now, this sounds interesting but trust me, don’t use the em unit. It becomes really messy if you start using it in a nested HTML structure. The following example demonstrates it very nicely.

rem

This is a better version of em, it works just like em, but instead of being parent element relative, rem’s are always relative to the font-size of the root element i.e. HTML tag. So by default the HTML font-size is 16px so 1rem = 16px unless the HTML documents font-size is changed. Example:

Conclusion:

First thing, try not to use em. Go with rem or px units. Now the place where rem becomes really useful is when it comes to responsiveness. So for eg on a bigger display if you change the default font-size of the browser, then the px unit will not scale, but if its rem then it would scale.

cssrempxemunitshtml