Update your font-size to REM units

A lot of websites are using pixel units that are difficult to adjust in the increasing variety of different devices.

CSS3 introduces a few new units, including the REM unit, which stands for “root em”.

So, how are we using REM ?

let’s say we have this CSS:

CSS

article h2 {font-size:20px;}
article p {font-size:12px;}

First of all we need to decide what size of px will be relative to all font’s. and to make it easy, the best practice I have done is to make root font-size 1px like this:

CSS

html {font-size:1px;}

Second of all we need to replace the rest of the font size values from pixel to rem units.

CSS

article h2 {font-size:20rem;}
article p {font-size:12rem;}

What REM does, it takes 20REM and Multiply it with the root element:

20 REM * 1 PX = 20PX.

Browser support

IE7 & IE8 still need to use PX values. This will force us to write font size twice, one time in PX and second time with REM.

CSS

article h2 {font-size:20px; font-size:20rem;}
article p {font-size:12px; font-size:12rem;}

LIVE EXAMPLE

Why REM units are good for you?

Lets assume we need to enlarge all fonts in our website by 20%, all we have to do is to change the size of the font-size in the root element, like this:

html {font-size:1.2px;}

If you wand to reduce by 20%, you will do it like this:

html{font-size:0.8px;}

Really nice and easy!

REM for Responsive Design

When you want to change all font size according to breakpoints in your responsive design it is a lot more easy. See example:

@media (min-width: 320px){
html{ font-size:1.4px; }
}
@media (min-width: 600px){
html{ font-size:1.2px; }
}

Now in smaller screens we re-size all fonts by 40% bigger, and in medium screens we re-size it by 20% bigger.

Using less to resolve the needs of writing everything twice — for supporting old browsers

in less or sass you can add functions to save you the time of writing everything twice.

less — font-size function and calling It

.font-size(@font-size) { 
font-size : @font-size * 1px;
font-size : @font-size * 1rem;
}

article h2 { .font-size(20); }

The compiled CSS will look like this:

article h2{
font-size:20px;/*Support IE7 & IE8*/
font-size:20rem;
}

Enjoy!

If you like this tip, I will be happy to get your LIKE. You are welcome to follow me and endorse my skills.

Elad Shechter


Originally published at coderwall.com by me, on May 28, 2013.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.