in CSS3

REM and EM in CSS

REM AND EM

One of the most confusing aspects of CSS styling is the application of the font-size attribute for text scaling. In CSS, there different units, pt, px, em and %, by which you can measure the size of text as it’s displayed in the web browser. Which of these four units is best suited for the web? Nowadays scaleable units are most popular. In this context REM and EM in CSS get its prominance. EM is scalable, but in CSS3 ther is a new unit called ‘REM’.

What is REM and EM in CSS?

Let us try to understand REM and EM for its proper usage in our development activities.

EM

The “em” is a scalable unit that is used in web document media. The “em” value is based on the width of the uppercase M. An em is equal to the current font-size, for instance. If you haven’t set font size anywhere on the page, then it would be the browser default, which is probably 16px. So by default 1em = 16px. If you were to go and set a font-size of 20px on your body, then 1em = 20px. Ems are scalable in nature, so 2em means 2 times the size of the current font. Ems are becoming increasingly popular in web documents due to scalability and their mobile-device-friendly nature.The ’em’ is a very useful unit in CSS, since it can adapt automatically to the font that the reader uses.

Example

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

If the browser default font-size is 16px, 62.5% of 16 is 10px. So 1 em is 10px. Same way, 2.4em is 24px, 1.4em is 14px.

REM

REM stands for ‘Root EM’. REM unit allows you to define a root em unit value on the html element, then use values on subsequent elements that are relative to the specified root unit. CSS rem unit to scale specific page elements while leaving others unaffected.

Why REM?

One of the problems with using “em” as font sizes is that they cascade, so you are forever writing rules that select nested elements to reset them back to 1em. The Problem with em-based font sizing is that the font size compounds. A list within a list isn’t 14px, it’s 20px. Go another level deeper and it’s 27px! These issues can be worked around by declaring any child elements to use 1em, avoiding the compounding effect. CSS3 now has rem (“root em”) to prevent that issue.

Example

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

Browser Support

All the latest browsers suppot ‘rem’ unit. For browsers which does not support ‘rem’ unit, we have to use fallback option with ‘px’.

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

More css tricks and tips

Related Posts

Written By:

2 Comments

  1. Rohan May 4, 2016 Reply
    • cssstarsAuthor May 4, 2016 Reply

Add a Comment

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