Visualizing the Difference Between em and rem Units in CSS
Posted on
When I was first learning CSS, the first 2 sizing units I learned were px
and em
. Since em
units are relative, I have always preferred using them whenever it makes sense. However, it took me years to fully understand how they work. When styling web pages, I used to just fiddle with numbers until I got something to look close to how I wanted, and I just accepted that this was how it was supposed to be.
I remember learning about rem
units for the first time and being really confused about how they are different from em
units. The difference is, of course, that em
units are relative to the font size of their parent element, and rem
units are always relative to the root font size. Looking back, I think the way rem
works is how I started out thinking that em worked. I guess it took me learning about rem
to finally realize that I didn't understand em
units.
At the time, I put together the example below to help me visualize how these units are different, and it really helped!
rem
font-size: 2rem
font-size: 2rem
font-size: 2rem
em
font-size: 14px
font-size: 2em
font-size: 2em
I've had this buried in a folder on my laptop for years, and I figured this was a better home for it. I think little experiments like this are a great way to get started with something new.