There are rems and ems, which a somewhat similar, but with their distinct differences.
What is a rem?
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, it’s a good read.
But why rems over pixels?
- Internet Explorers can’t resize pixel set type.
- It doesn’t cascade (more on that later).
But why rems over ems?
All the IEs play nicely with ems 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.
Why is cascading so important?
Sometimes you want type to be bigger or smaller depending on the screen size.
With rems you can just change the value in the root element and all text down
the line will resize. Simple and effective. For a Sass pattern that keeps those
breakpoints close to the styles they affect, see
writing media queries with Sass.
@media screen and (max-width: 639px) {
/* Make the type a bit smaller small screens */
body {
font-size: 0.7rem;
}
}Setting it all up
The article that I quoted earlier 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 trick to get the rem and em values look nice, so that the
code is easy to maintain. For instance, 1.4rem equals 14px, whereas 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.
We can do the calculation with SASS, we can have the cake and eat it too, so to speak:
// 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.
Further reading and sources
- Font sizing with REM
- Some forum discussion about the 62,5% base thing
- More forum ranting
- A List a Part article from 2007, talking a lot about IE6 and IE7, not so relevant anymore but still a good read
- CSS-Tricks article wondering the sizing in em
- pxtoem.com
emtopxconversion tool - Another
emcalculator - Aaaand, I think this article:
How to size text using ems is the one that
started the
62.5%base thing back in 2004.