Reasons to Use em in CSS Instead of px
One of the most common questions newcomers ask about CSS is why they should use em when defining distances and sizes in their style sheets. After all, pixels (px) have long been the standard unit of measurement in web design, so what’s the purpose of using em? While both px and em can be used to define distances and sizes, em is the preferred choice for a few different reasons.
Absolute vs Relative
It’s important to understand that px is an absolute unit of measurement, whereas em is a relative unit of measurement. When you define an element in a style sheet using px, it will remain this size regardless of the user’s browser or device. Now if everyone who accessed your website used the same browser and same display device, this wouldn’t be a problem. But this isn’t the case, and different visitors will use different browsers and devices, resulting in broken design elements due to the fixed units of measurements defined in the style sheet.
Em is classified as a relative unit of measurement, meaning it is proportionate to its respective font size. As explained by SitePoint, an em unit is the equal to the font-size for the element to which it is applied. So when you apply an em unit on a child element that doesn’t already have a font size defined, that element will inherit its font size from the parent. Technical jargon aside, px is an absolute unit of measurement that never changes, whereas em is proportionate to the declared font size.
When to use px
There are some instances in which px is the preferred unit of measurement, such as adding banners or logos to a webpage. If you want a particular image “fixed” in an area, it’s best to use px so it doesn’t float around based on the user’s browser or device.
Mobile Compatibility
Google recently announced that more Internet searches are performed on mobile devices in 10 different countries (including the U.S.) than desktop devices. Websites that are designed entirely with absolute units of measurement (e.g. px, cm, or pt) will not automatically adjust based on the user’s device. Even if a website looks fine when accessed on a 21″ computer monitor, it may render poorly on a smartphone or tablet. This is why it’s a good idea to use em to define distances in web design instead of px. Using relative units of measurement like em, rem and percentages, websites will scale up and down to ensure a smooth, positive viewing experience.
Thanks for reading, follow your passion by finding the perfect course, just for you over on www.stoneriverelearning.com.
GET YOUR FREE HTML5 & CSS3 EBOOK!