What is the difference between the em and rem unit in CSS?

What is the difference between the em and rem unit in CSS?

One of the most difficulties new web developers encounter while making a web page is whether using em or rem as the size unit. Let's dive into understanding the difference between them.

em

em is a unit that takes the value of the parent element's font size as the base size. For example

card {
    font-size: 16px;
}

.card-title {
    font-size: 1.5em; // 16px * 1.5 = 24px
}

.card-desc {
    font-size: 0.8em; // 16px * 0.8 = 12px
}

With that example, the element with class card-title and card-desc will have 24px and 12px respectively. If the parent element has not specified a value for font-size, a value will be looked for higher up in the DOM tree. If no font-size is specified all the way up to the root element (), then the browser default of 16px is used.

rem

rem stands for 'root element' which is element. It takes the unit value based on the font-size given to the root element. So that means that, by using the rem unit, the values of parent elements are ignored, and only the value of the root is taken into consideration.

html{
    font-size: 16px;
}

card {
    font-size: 20px;
}

.card-title {
    font-size: 2rem; // 16px * 2 = 32px
}

.card-desc {
    font-size: 0.8rem; // 16px * 0.8 = 12px
}