A good[ish] website
Web development blog, loads of UI and JavaScript topics
It’s slightly mysterious, to use ems or px, or maybe rems?
The thing is...
But...
I quote:
The rem unit is relative to the root—or the html—element. That means that we can define a single font size on the html element and define all rem units to be a percentage of that.
It’s taken from this article, I recommend reading it.
All the IEs play nicely with em
s and they cascade good, but...
The problem with em-based font sizing is that the font size compounds. A list within a list isn’t 14px, it’s 20px. Go another level deeper and it’s 27px!
You can easily get over it but it’s still a drag.
Sometimes you want type to be bigger or smaller depending on the screen size. With rem
s you can just change the value in the root element and all text down the line will resize. Simple and effective.
@media screen and (max-width: 639px) {
/* Make the type a bit smaller small screens */
body {
font-size: 0.7rem;
}
}
The article that I quoted earlier (really nice read), uses the font-size: 62.5%;
baseline thing, which might be needed or not (the article was written in 2011).
html {
font-size: 62.5%;
}
We use that above "hack" to get the rem
and em
values look nice, so that the code is easy to maintain. For instance 1.4rem
equals to 14px
, where as normally it would be something totally wild like 0.875rem
. If we’d want to change the font size for a given site that uses the wild rem
or em
values, we’d need to learn that new scale, or use a conversion tool.
Since we got SASS now, that can do the calculation, we can have the cake and eat it too:
// Function for converting a `px` based font-size to `rem`
@function calculateRem($size) {
$remSize: $size / 16px;
// Default font size on html element is 100%, equivalent to `16px`
@return #{$remSize}rem;
}
// Mixin that will include the fallback `px` declaration, as well as the
// calculated `rem` value
@mixin fontSize($size) {
font-size: $size;
font-size: calculateRem($size);
}
Usage:
@include fontSize(14px);
You may also wanna take a look at the rem browser compatibility table.
em
to px
conversion toolem
calculator62.5%
base thing back in 2004.Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.