HTML & CSS Interview Question #70
What is the difference between em and rem units?
CSS Fundamentals, Selectors, Cascade, Specificity, Box Model, Units & Typography Mid-Level Intermediate
Quick Interview Answer
em is relative to the relevant font-size context. For font-size itself, it is based on the parent element's font size; for many other properties, it is based on the element's computed font size. Nested em-based sizing can therefore compound.
Detailed Explanation
em is relative to the relevant font-size context. For font-size itself, it is based on the parent element's font size; for many other properties, it is based on the element's computed font size. Nested em-based sizing can therefore compound.
rem is relative to the root element's font size. It is often convenient for consistent application-wide typography and spacing because it does not compound through nested components in the same way.
Code Example
html {
font-size: 16px;
}
.card {
font-size: 1.25rem; /* 20px if root is 16px */
padding: 1em; /* relative to card font size */
}
.title {
font-size: 2rem;
}