Making Ems for Font Size Human Friendly

May 19, 2017

Ems are great for todays web due to the necessity of responsive designs. Instead of changing each elements pixel font size with media queries to accommodate the differences between mobile and desktop, Ems or Rems allow you only need to change the font size on the <body> element and all of the changes will trickle down automatically, preserving relationships and ratios.

However the draw back has always been calculating what to set the initial value for each element. Let’s say you have a base size of 16px and want an <h1> of 26px, you’d need to divide 27 by 18 and get a value of 1.5. So the css would look like this:

body {
  font-size: 18px;
}

h1 {
  font-size: 1.5em; /*target size 27px*/
}

While this isn’t difficult to do it takes time to translate each value from a design file. Not to mention the unpleasant times when the math doesn’t work out nicely:

body {
  font-size: 18px;
}

h1 {
  font-size: 1.5em; /*target size 27px*/
}

h2 {
  font-size: 1.166em; /*target size 21px*/
}

Not to mention dealing with nested elements where the Ems stack on top of one another.

body {
  font-size: 18px;
}

h1 {
  font-size: 1.5em; /*target size 27px*/
}

h1 span {
  font-size: 1.185em; /*target size 32px, 32/27 = 1.185185... */
}

h2 {
  font-size: 1.166em; /*target size 21px*/
}

Sass to the Rescue!

With Sass we can set up a quick function to do all this math for us.

$font-size: 18;

@function em($target, $context: $font-size) {
  @return ($target / $context) * 1em;
}

body {
  font-size: $font-size#{px};
}

h1 {
  font-size: em(27); /*target size 27px*/
}

h1 span {
  font-size: em(32,27); /*target size 32px, closest parent is 27px*/
}

h2 {
  font-size: em(21); /*target size 21px*/
}

By using our custom em() function, Sass does the math for us. The function can take 1 or 2 inputs, the desired font size as the $target variable, and if there is a parent whose font-size we’ve already manipulated as the $context. If there is no $context it will default to the base $font-size variable we declared and is attached to the .

So now we can utilize the ease of pxss but with the efficiency of ems.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive