Middle
Tell about units of measurement REM and EM in CSS: what are they and how do they work?
sobes.tech AI
Answer from AI
REM and EM are relative units of measurement in CSS, which depend on the font size and are used to create responsive and scalable layouts.
-
EM is a relative unit based on the font size of the parent element. For example, if the parent has font-size: 16px, then 1em = 16px. If a child element has font-size: 1.5em, its size will be 24px.
-
REM is a relative unit based on the font size of the root element (
<html>). Browsers typically set the font-size for<html>to 16px by default, unless overridden. 1rem always equals the font size of the root, regardless of nesting.
Differences and applications:
- EM depends on the nesting context, which can lead to cascading increases in size if multiple levels are used.
- REM is more predictable as it always refers to the root, making it convenient for global size management.
Example:
html { font-size: 16px; }
.container { font-size: 1.5rem; /* 24px */ }
.container p { font-size: 1em; /* 24px, since 1em from .container */ }
.container p span { font-size: 2em; /* 48px, 2 * 24px */ }
Using REM is convenient for global interface scaling, while EM is suitable for local scaling relative to the parent.