Main Navigation

Main Content

How I setup my font sizes

CSS Tutorial Featured Image

I have seen so many different ways to setup font sizes within a stylesheet, but my preferred method is the following:

html {
    font-size: 62.5%;
}

The beauty of doing it this way is purely to keep the maths simple, you can now accurately set your font sizes as em’s by dividing the px value by 10. For example in Photoshop if the main font size was 14px we would write this as 1.4em. 12px would be 1.2em etc.

body {
    font-size:1.4em;
}

It gets better…

Using em’s is great, they resize nicely in the browser making them highly accessible, but they also have this really annoying problem where the em values of different elements that are placed within each other can multiply and give you incorrect text sizes which then have to be reset. In fairness this isn’t too hard to manage, though things can get a little tricky when dealing with really deep nested lists containing lots of different styles of text. Luckily thanks to CSS3 there is a solution…

body {
    font-size: 1.4rem;
}

Using rem’s means the font size is always relative to the root. This means that other rem sizes will not interfere and even the most deep nested paragraph tag will always remain the correct size. The only problem here is support and I believe that IE7 and 8 (surprise surprise) won’t understand this unfortunately. To get around this however we can use px as a fall back:

body {
    font-size: 1.4rem;
    font-size: 14px;
}

The icing on the cake

To save time there is a SASS mixin that you can use for declaring font sizes, it also helpfully outputs the line-height as well. If you don’t use SASS then I highly recommend taking a look, you can find some great tutorials from Level Up Tuts on Youtube. The mixin is as follows:

@mixin font-size($fontSize: 1.6, $lineHeight: $fontSize * 1.5){
    font-size: ($fontSize * 1) + px;
    line-height: ($lineHeight * 1) + px;
    font-size: ($fontSize / 10) + rem;
    line-height: ($lineHeight / 10) + rem;
}

You would then call this using:

body {
    @include font-size(14, 16); // Notice that we enter the actual pixel values (font-size, line-height)
}

This will output the rem values along with the px fallback, job done.

body {
  font-size: 14px;
  line-height: 16px;
  font-size: 1.4rem;
  line-height: 1.6rem;
}
comments powered by Disqus

Sub Footer