In CSS, both em and rem are relative units used to set properties such as font size, padding, and margin for elements. The primary distinction is that em is relative to the parent element's font size, whereas rem is relative to the root element's font size.
em Unit
The em unit is defined relative to the parent element's font size. For example, if a parent element has a font size of 16px, then 1em equals 16px. If a child element inside this parent has its font-size set to 2em, the child's font size will be 32px (16px * 2).
- Example: Consider an HTML structure with a paragraph
<p>inside adivcontainer. Thedivhas a font size set to20px, and the paragraph's font size is set to1.5em. The actual font size of the paragraph will be30px(20px * 1.5).
html<div style="font-size: 20px;"> <p style="font-size: 1.5em;">This is a paragraph.</p> </div>
rem Unit
The rem unit is defined relative to the root element (i.e., the HTML element)'s font size. Regardless of the document hierarchy, 1rem always has the same value, determined by the root element's font size.
- Example: If the HTML element's font size is set to
16px, then1remequals16pxat any position in the document. No matter how deeply nested,remis based on the root element's font size.
html<html style="font-size: 16px;"> <body> <div style="font-size: 20px;"> <p style="font-size: 1.5rem;">This is a paragraph.</p> </div> </body> </html>
In this example, regardless of the div's font size, the paragraph's font size remains 24px (16px * 1.5) because it is calculated based on the HTML element's font size.
Usage Scenarios
- em: Use
emwhen you want element styles (such as font size and spacing) to be closely related to the parent element's font size. - rem: Use
remwhen you need a consistent layout without being affected by the parent element's font size. It ensures uniform font size across the entire page, especially valuable in responsive design.
In summary, understanding and choosing between em and rem depends on whether you want the styles to align with the parent element's font size or the root element's font size.