Using rem units

What are they?

rem is a CSS3 unit which can be used instead of the em and px units. rem stands for “root em”.

Why use the rem unit?

Like the em unit, the rem unit is useful in responsive design. But whereas the em unit is relative to the font-size of it’s parent, the rem unit is relative to the root or html element.

That means that we can define a single font size on the html element and define all rem units to be a fraction/multiple of that and not have to worry about units compounding as they do with the em unit.

Here is a basic example of rem usage.

html { font-size: 62.5%; } 
body { font-size: 1.4rem; } /* = 14px */
h1   { font-size: 2.4rem; } /* = 24px */

A base font-size of 62.5% is used so we have the convenience of sizing the rem units in a way that is similar to using px.

font-size: 100% is equal to font-size: 16px in most browsers. 62.5% of 16px is 10px. So 1rem would equal 10px and 2rem would equal 20px etc.

Browser support

The rem unit is not supported by IE8 and below. To overcome this, a pixel unit fall-back needs to be declared. SCSS mixins can make this a little easier.

html {
    font-size: 62.5%; /* = 10px; */
}

/* Declare the mixin with a default value of 16 for it's $pixels argument */
@mixin font-size( $pixels: 16 ) { 

    /* Convert the $pixels value to px units using the + operator */  
    font-size: $pixels + px; 

    /* Convert the $pixels value to rem units.  */
    font-size: (pixels / 10) + rem; 

}

The following is an example of how to use the mixin if you want a want a font-size of 20px and 2rem.

p {
    @include font-size(20);
}

 

References:

Leave a Reply

Your email address will not be published. Required fields are marked *