Sizings Using Px, Em And Rem

Understanding the concepts behind the various CSS units

Sizings Using Px, Em And Rem

Using px

Pixels is a CSS unit used on websites. Pixel unit is usually fixed and does not change based on any other elements. It can be a problem for responsive sites but they are useful for maintaining consistent sizing for some elements. If you have elements that should not be resized, then using pixels is a good choice.

<div>
  I am 16px by default
</div>
<div class= "style">
  I am 20px by styling
</div>
.style{
  font-size:20px
}

pixel.PNG Codepen

Using em

EM is a CSS unit that is relative to the parent’s element. It is better suited to responsiveness design and also help meet accessibility standard. Relative units scale better on different devices because they can scale up and down according to another element size. In most browsers, the default font size is 16px , therefore relative units calculate the size from this base.

The number you specify will multiply that number times the default size.

1em = 16px --> (1 x 16)

2em = 32px --> (2 x 16)

<div class= "parent">
  I am 16px by default
  <div class= "child">
  I am 32px
    <div class= "child">
  I am also 32px and this is unexpected
    </div>
  </div>
</div>
.parent{
  font-size:16px
}
.child{
  font-size:2em
}

em.PNG Codepen

Using rem

Rem differs based on inheritance. While em is based on the parent element, rem is based on the root HTML element. Every child elements that uses rem will then use the HTML root size as its calculation point, regardless of whether or not a parent element has any different sizes specified.

<div class= "parent">
  I am 16px by default
  <div class= "child">
  I am 80px
    <div class= "child">
  I am also 80px
</div>
</div>
</div>
html{
  font-size: 40px;
}
.parent{
  font-size:16px
}
.child{
  font-size:2rem
}

rem.PNG Codepen

Understanding the concept behind the use of pixels, em and rem becomes clearer with usage and practice overtime. If you found this article helpful, please do well to share and I would appreciate your feedback too on which units you prefer and why.

Keep learning! Keep coding!! 💛