clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Sizing type on the web

Filed under: Styling— Tagged with: typography, sass, CSS

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.

@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 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.

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);
}

Source

Usage:

@include fontSize(14px);

You may also wanna take a look at the rem browser compatibility table.

Further reading and sources

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!