Greg Rickaby

Greg Rickaby

Cameras and Code

Web Typography: Using The Golden Ratio and REM’s

When WordPress 3.5 beta 1 was released it came with, “Twenty Twelve”. While looking at style.css, I noticed the use of “REM” to set font sizes and margins. I had NO idea what REM was. In fact, I just started using EM’s in other child themes. Immediately, I turned to Google and started researching.

I thought REM was a band?

By definition, the REM unit is: “Equal to the computed value of ‘font-size’ on the root element. When specified on the ‘font-size’ property of the root element, the ‘rem’ units refer to the property’s initial value.

tl;dr The REM is one of the newest font-size standards for CSS3. It stands for “Root EM”. You base your calculation on the default font size of the HTML element – NOT the parent-like EM. It’s basically “EM v2.0”.

So what?

The problem with Pixels is, they absolutely do-not-scale in Internet Explorer. Furthermore, with the onset of Responsive Web Design, having fonts that scale (in relation to the screen width) has become paramount. Percentages (%) and EMs are better, but they’re tricky and compound. Still not an answer. A real solution?

Use the REM

First, you need to set a default “root” font-size variable:

html {
    font-size: 62.5%
}

Why 62.5% instead of 100%? Simplicity.

Our default font is now 10px, which makes math easier. Now, 1.0rem = 10px. This becomes our $rembase.

Calculate other font sizes by dividing your desired size by the $rembase (in pixels). Let’s say, you want your <h1> tags to be 26px:

26 ÷ 10 = 2.6rem

or

32 ÷ 10 = 3.2rem
48 ÷ 10 = 4.8rem

and so on…Let’s take a look at a sample Stylesheet:

/* $rembase = 10px */

html {
    font-size: 62.5%;
}

body {
    font-family: 'Helvetica Neue', Arial, sans-serif;
    font-size: 1.0rem; /* 10 ÷ $rembase */
}

h1,
h2 {
    font-size: 2.6rem; /* 26 ÷ $rembase */
}

h3,
h4 {
    font-size: 1.8rem; /* 18 ÷ $rembase */
}

That looks simple enough, right? Just move the decimal. Now your fonts will scale perfectly during a browser re-size (if using responsive design), or if a user were to zoom in or out.

But what about Line Height?

Line heights have always given me headaches, that was until Chris Pearson released his Golden Ratio Typography Calculator. Now, figuring out line heights (among other settings) is a snap.

  1. Input your desired font size (16px)
  2. Specify how wide your content box is (mine is 740px)
  3. Click “Set my type!”

The Golden Ratio Typography Calculator spits out optimized typography values:

The calculator tells us our default line-height should be 26px. This variable is the $line-height-base.

We’re going to be using “Unitless line heights” as explained by Eric Meyer, so we can avoid unexpected results. What’s so awesome about the unitless line-height? You only have to specify it once in the <body> tag. Now, ALL other line-height(s) are relative to the parent font size. That’s too easy! (Of course, you can still specify your own to maintain complete control.)

To calculate, you divide the $line-height-base by the font size for that particular element (in pixels).

26 ÷ 16 = 1.625

How would that look in our sample style sheet?

/*
$fontbase = 16
$line-height-base = 26
*/

html {
    font-size: 62.5%;
}

body {
    font-family: "Helvetica Neue", Arial, sans-serif;
    font-size: 1.6rem;
    line-height: 1.625; /* $line-height-base ÷ $fontbase */
}

h1,
h2 {
    font-size: 2.6rem;
    line-height: 1; /* $line-height-base ÷ 26 */
}

h3,
h4 {
    font-size: 1.8rem;
    line-height: 1.444 /* $line-height-base ÷ 18 */
}

Note: We’ll only use three decimal places to the right since most browsers only calculate that far.

What about margins?

Yes, you can even use REM to set your margins. Margins, or “vertical spacing” is calculated using either 24px or 48px to maintain vertical rhythm. Let’s divide 24px by our $rembase:

24 ÷ 10 = 2.4rem

Here’s our sample stylesheet:

/*
$rembase = 10
$line-height-base = 26
*/

.some-div {
     margin: 2.4rem 0; /* 24 ÷ $rembase */
}

.another-div {
    padding: 4.8rem; /* 48 ÷ $rembase */
    margin-bottom: 2.4rem; /* 24 ÷ $rembase */
}

I’m convinced, now tell me about browser support.

At the time of writing: REMs are supported in Firefox, Chrome, Safari, Opera, and yes, even IE 9 & 10. It’s also supported in all mobile browsers except for Opera Mini.

Check out this list: http://caniuse.com/rem

What about fallbacks?

As is the case with most CSS3 wizardry, REM support in IE 6, 7, and 8 is lacking and will require a PX fallback. By declaring REMs after PXs in the CSS this example  will degrade gracefully to the PX:

html {
    font-size: 62.5;
}

body {
    font-family: "Helvetica Neue", Arial, sans-serif;
    font-size: 16px;
    font-size: 1.6rem;
    line-height: 1.625;
}

h1,
h2 {
    font-size: 26px;
    font-size: 2.6rem;
}

h3,
h4 {
    font-size: 18px;
    font-size: 1.8rem;
    line-height: 1.444;
}

.some-div {
     margin: 24px 0;
     margin: 2.4rem 0;
}

The purpose of this post was not to stand on a soapbox and preach but educate you on the advantages of using REMs to enhance the typography on your site. Your comments are welcome below.

PX to REM Sass Mixin

// Create REM values with PX fall back
//
// Generate a REM with PX fallback from 
// $baseFontSize. Enter the desired size based
// on pixels in numerical form. Supports shorthand.
//
// Forked from: http://codepen.io/thejameskyle/pen/JmBjc
//
// @author Greg Rickaby
// @since 1.0
//
// Usage: @include rem($property, $values);
// Example Usage:
//    @include rem(font-size, 16px);
//    @include rem(margin, 0 24px 0 12px);
//
// Outputs:
//    font-size: 16px;
//    font-size: 1.6rem;
//    margin: 0 24px 0 12px;
//    margin: 0 2.4rem 0 1.2rem;
// ----------------------------------
$baseFontSize: 10; // Based on HTML reset html { font-size: 62.5%; }

@function parseInt($n) {
  @return $n / ($n * 0 + 1);
}

@mixin rem($property, $values) {
	$px : (); 
	$rem: ();
	
	$root: $baseFontSize;
	
	@each $value in $values {
		@if $value == 0 or $value == auto {
			$px : append($px , $value);
			$rem: append($rem, $value);
		}
		
		@else if type-of($value) == number { 
			$unit: unit($value);
			$val: parseInt($value);
			
			@if $unit == "px" {
				$px : append($px,  $value);
				$rem: append($rem, ($val / $root + rem));
			}
			
			@if $unit == "rem" {
				$px : append($px,  ($val * $root + px));
				$rem: append($rem, $value);
			}
		}
		
		@else {
			$px : append($px,  $value);
			$rem: append($rem, $value);
		}
	}
	
	@if $px == $rem {
		#{$property}: $px;
	} @else {
		#{$property}: $px;
		#{$property}: $rem;
	} 
}

@function rem($value) {
	$root: $baseFontSize;
	$val: parseInt($value);
	$return: ();
	
	@if unit($value) == "px" {
		$return: append($return, ($val / $root + rem));
	} @else {
		$return: append($return, ($val * $root + px));
	}
	
	@return $return;
}

Further reading

Category: Code

Tags: how to, typography

Comments

Nectafy (@nectafy)

Greg,

Thanks for spelling all of that out. Font sizes in responsive design have been problematic for me. This will help!

Lyfe

Thanks from the noob, Now that i can actually wrap my head around this.
Im going to do a total re-haul of my project site. Also thanks for pointing
me to the Golden Ratio Calculator.(plus links). Im Psyched and Ready.

THANKS

Chris Pearson

As a longtime fan of ems (and relational sizing in general), I am also quite interested in rems, which are, in my opinion, “ems done right.”

Over the past 18 months, I spent a lot of time testing different CSS approaches to see which I would use in Thesis 2 and associated Skins. Specifically, I was looking to see how I could transition from ems to rems, and that’s when I learned some unsettling stuff.

First, you mention Eric Meyer’s “unitless line heights” as a potentially simpler way of expressing line-heights. Because omitting units is simpler than including them, I was originally drawn to this technique as well.

However, upon testing, I became quite disappointed because I learned that browsers are extremely inconsistent with their handling of unitless line heights.

Though I don’t remember the precise results of my testing, I know that Chrome, Firefox, Safari, and IE all had different interpretations of unitless line heights. Chrome, my browser of choice, was extremely bad, oftentimes missing the resulting line height by a pixel or more.

For some people, one pixel off is no big deal. For me, it’s the difference between repeatable, predictable precision and an arbitrary crapshoot.

Given this information, I had to accept the fact that unitless line heights simply aren’t consistent enough to be included in a mass-distributed product like Thesis.

This was only a minor setback, though, because I really wanted to use rems or, in a worst-case scenario, ems (like I’ve done in my distributed products since 2006).

To make a long story short, my em/rem testing revealed more of the same browser inconsistencies. Again—and to my surprise—Chrome was the worst offender.

Here’s the precise situations where Chrome fails miserably:

If you are using rems or ems, and the *calculated line height* (that is, the numeric value the browser arrives at after multiplying your em/rem base by the line-height ratio) is less than the nearest integer, Chrome fails to round properly and instead truncates.

So, in a situation where the line height calculates to something like 21.999px, instead of correctly rounding that line height to 22px on screen, Chrome renders a 21px line height.

Fail.

The entire point of Golden Ratio Typography is to achieve a precise geometrical layout whose dimensions are informed by mathematical relationships.

If browsers cannot calculate the input maths properly, then this entire approach is undermined.

Through my own testing, I’ve determined that the only way to achieve precisely-calculated line-heights at this point in time is to use pixel values.

Browsers—mobile devices included—show almost no variance when pixels are the input basis. However, switch to unitless line-heights and/or ems/rems, and you’ll begin to notice all sorts of browser irregularities in your testing.

This is yet another area of web design/development where the specifications and possibilites far outpace the reality within which our products actually live.

Miketee

Line-height: 24px; for the win, you you stay right in the baseline ( until you start using a border bottom it throws it off by a pixel :p )

Todd

Chris, Is line height still a problem in Chrome where you still use pixel values?

Miketee

Only problem I find, and I continuously battle with this, but your vertical rhythm has been thrown off by using the correct golden ratio of 26 for the line height. Because your margin bottoms are 24.

Josh Stauffer

Greg, thanks for this informative post on REM’s.

One note on the comment regarding vertical rhythm. I believe the 24px and 48px is dependent on your line-height. In your examples, you are using a line-height of 26px so I think the values should be 26px and 52px to maintain that rhythm.

Thanks again!

skube

I guess what is confusing me is that paragraphs within the body are computed to a larger size by default, unless specifically defined. For example, is your styles are simply:
html {font-size:62.5%}
body {font-size: 11px; font-size:1.1rem}

Paragraphs will show up as 18px (at least in Chrome) for some reason.

Jitesh Patil

Jitesh Patil

Greg, Thanks for the article. It really helped me understand GRT.

I have a few question though.
1. When using GRT is vertical rhythm important?
2. Why don’t site’s built on thesis/genesis follow vertical rhythm?

Sam

Hey Greg,

Love this article, thank you for explaining everything in black and white.

There appears to be a new bug in Chrome. On random occasions, Chrome ignores html{ font-size: 62.5%;} and renders huge font. This doesn’t appear to be happening in any other browser.

S

L. Von Nachtosphere (@nobilelucifero)

Nice article. For the re-size/zoom paragraph I permitted myself to do a small demo, so who is new to the argument can get better the idea. http://cdpn.io/EzKIv

I used this property of REMs in some Mobile/Responsive Interfaces prototypes with quite interesting results!

P.S.: Mathematical favicon Greg!

Kenny

This is absolutely fantastic. After reading the “Ultimate Guide to Readable Web Typography” on the Pearsonified blog years back I was really intrigued and wanted more. Tonight, I just happened to stumble on this article and I think you just changed my unit of choice for good. Incredible article, and setting the root font size to 62.5% is a brilliant little trick…I feel like I just witnessed a goose laying a golden egg.

Alex

Thanks so much! This was extremely helpful (probably the most helpful article I’ve read on this topic), especially regarding rem in relation to line-height. I’m looking forward to getting down to work and making some significant changes in my current project.

Lubos

Hi, I just stumbled across this article. Good stuff.

I’m just having trouble finding the visual appeal of having uniformly line-spaced h1-h6 elements, like we have in the Golden Rule Generator and in your method, using the multiples of your “base”. I want to point out where we either a) run into problems with the spacing or b) need extra CSS formatting.

a) With both methods we have problems when a heading spans more than one line. With the golden ratio approach, we have far too large a gap between the first and 2nd line of the same header element. In your approach, the lines are actually scrunched in too much (for example, Times/Baskerville at 36px results in a line-height of 0.667 when using your approach). Both outcomes are not visually pleasing and would need to be addressed in your style sheets.

b) I just want readers to know that this isn’t a complete solution, and these typographical issues should be addressed in their styles:

When we have uniform spacing between the end of one paragraph, a new subheader, and the beginning of a new paragraph, we’re being a bit too robotic about the whole approach.
Ideally you want to anchor your subheader closer to the beginning of the content that follows it – to add some visual relation. This isn’t so bad at all when you have a content-rich page like this one, where you might have code snippets, quotes or images, but take a look at the first few paragraphs and headings of this page – imagine a longer article laid out like this and you’ll see what I mean about it being a robotic approach. To address this, you could just add a margin after each p element (browsers do this by default but your style sheet may have stripped it out).

Secondly, the uniform spacing approach by itself is not good for a title-subtitle relationship. Many times we want a title and subtitle to be nestled closely together, which will also require extra styling. You can do this by placing both inside an hgroup element, then using a CSS selector like this:

hgroup > h1 { margin-bottom: 0; }
hgroup > h2 { margin-top: 0; }

Or you can go all advanced on us and use fancy pseudo-class selectors without requiring an hgroup element.

One more thing for readers to consider is that text-grouping elements do have their own style conventions inside browsers. For example, the aforementioned p elements have a margin-after of 1em, h1 elements have both a margin-before and margin-after of 0.67em, and so on. You’ll need to address those in your stylesheets as well if you’re not seeing the desired results when using the code from this page.

Ellis

I just wanted to touch briefly on what Lubos above mentioned; with an addition. I would never use a ratio of anykind, golden, root, whatever, to drive typographic decisions. Typefaces are unique, imperfect, they are aesthetically, structurally, and mathamatically different, and designed that way, purposefully. Web Developers want to modularize everything, make things resuable, portable, which is awesome , when it makes sense, but when it comes to typography, it doesn’t.

In design school you study all of these things, sacred geometry, the golden ratio; through history, art, design, nature, etc. It has its place, and can be used to great effect, especially in manuscript, book, editorial design, sculpture, even the construction of a typeface itself, but while its proportions may be naturally beautiful, it does not mean, that everything applied to those constraints, or within them is, or will be. Good typography is hard, and ironically enough for this very reason.

When I look at the Golden Section Typography Calculator link from above, I immediatly think a lot of things, but one of them isn’t “this is beatiful typography”. In design school one thing you continually do are find examples of good and bad design, and articulate why it is which one. You develop a thick skin, let your guard down, so you can learn, progress, grow. You have to make calculated, thoughtful decisions, not arbitrary ones, or easy/lazy ones like letting the golden ratio define your type.

When I look at that page, I think its amateurish, lazy. It looks like someone spent a few minutes, chose the first fonts that popped up in a dropdown, and called it finished. It’s not horrible, but its not professional, refined, designed.

If I would have turned in work like that (Golden Section Typography calculator page) I would have gotten it back, littered with notes and changes. She also would have asked me why I chose that typeface for the heading, the body? Is a modern font a good fit? Why? How does it relate to the content? Does it really look “finely-tuned”, “sexy”? Should it look “sexy” at all? Explain…

My point is, the road to good, great, respectable, admirable, admired, beautifully legible typography is a long winding one, devoid of tools and ratios, and a default 16px, and dependent upon understanding the connection between letter-form, function, voice, and the relationship between that type, the page it resides in, the images surrounding it, the voice its communicating with, and the people that will be listening to, and reading it.

At the end of the day we separate ourselves into typographic groups; at one end, the satisfied and content, those that would have no problems with this text: http://cl.ly/image/3D0F0V141a2T, and at the other, the hungry ones, eager to recognize all the mistakes, and do.

Anyways, thanks for your time.
— Designer

p.s. (for the hungry ones… its in the double-digits)

Nickolas

Nickolas

Lubos above was on the right track as far as having uniform spacing with back-to-back headings, spacing and the like among other things.

Ellis above has the wrong idea in general.

There isn’t and shouldn’t be a systematic approach to every typographic choice; however, there are plenty of guidelines to base your choices off of and the rest are up to what it is exactly you’re trying to accomplish.

There are ratios and research studies for a reason (how long of a measure is too long?). Adding structure to any design is for a particular type of design and doesn’t mean you can’t create chaos outside of that concept by introducing off-beat leading or things of that sort.

It isn’t magical that we don’t have 100pt decenders on a 12pt paragraph and that’s for good reason. It’s not because one person pulled it out of thin air. Does that mean we can’t do that in any shape or capacity? No. It’s just not a practical purpose for legible paragraph text.

Ellis

You misunderstood. My post in general, and my point. Im not talking about line length or whatever it is your referring to regarding “length of measure”. Im not saying don’t use a guideline/framework/ratio, whatever, like TGR, but that, relying on those tools and accepting them as default n’ done, beautiful one-click type done, is the wrong way of thinking about/approaching it.

Regardless of where you start, default stylesheet/browser settings, or [some awesome ratio dating back to BC], it all needs adjustment; attention. Im just saying think about designing for the typeface and its characteristics first. That doesn’t mean you can’t [whatever your arguing for/against].

So what the hell am I talking about? A deeper relationship between type and page/screen. Im saying look at good typography and try to understand why it is. Im saying take the scenic route, stop taking shortcuts, and “someone” else’s word for it, just because they have “research studies”, whatever that means/is. But sure…I have the wrong idea.

“Has the whole world gone crazy” — William Foster

Jamaluddin Rahmat

Wow… The complete explanation.
I sometimes use REM but without know it functions.

Now I know about $rembase must be declare first for make easy customization of REM.

Thanks Greg.

SUapk

Font sizes in responsive design have been problematic for me. This will help!