EM vs. PX: Sizing HTML Elements in CSS

When defining an HTML element’s size — whether it’s a font size, the width or height of div, or the margin and padding of any particular element, you can use relative units like rem or em, or you can use a fixed unit, like px. Rem and em units are growing more popular as an ever increasing number of sites are becoming mobile-friendly. Em units are especially mobile-friendly because they define the size of an element as it relates to its parent element. So for example, if your css looked like this:

  1. html{
  2. font-size: 2em;
  3. }
  4.  
  5. p{
  6. font-size: .75em.
  7. }

The default font-size for your html would be 2em, which is the equivalent of about 32px. The font-size of your p elements would then depend on the font-size of their parent elements. So if the p element’s direct parent was the html or another element that inherited the html’s 2em font-size, the p element’s font-size would be 75% of 2em, or about 24px.

Join us in our newest publication:

These relative units are particularly useful in mobile styling because they have the potential to seriously condense our media queries. Let’s say that the font-size of your html was set to 32px, the font-size of your h1 elements was set to 24px, and the font-size of your p elements was set to 16px, but you wanted all of these sizes to be bigger on a mobile device. If you’re using px, then you have to write new CSS for each of these elements in your media queries, like this:

  1. @media screen and (max-width: 500px){
  2. html{
  3. font-size: 48px;
  4. }
  5.  
  6. h1{
  7. font-size: 32px;
  8. }
  9.  
  10. p{
  11. font-size: 24px;
  12. }
  13. }

That’s a lot of extra code. If you use ems, changing the font sizes for mobile styling becomes as simple as writing one line in your media query. For this example, let’s assume that the font-size for the html is 1em — the default size.

  1. @media screen and (max-width: 500px){
  2. html{
  3. font-size: 1.5em;
  4. }
  5. }

This way, all you have to do is define the html’s font-size in ems, and as long as the other html elements have font-sizes that are defined using ems, they will automatically scale accordingly.

There is also the option of using the rem unit (root em unit) in place of the em. The difference between rem and em is that em is always relative to the font-size of its most direct parent element, while rem is only relative to the root font-size, meaning the font-size of the <html> element.

 

Share and Enjoy !

0Shares
0 0