In CSS, rem is a unit of measurement that stands for “root em.” It is relative to the font size of the root element (<html>), making it a flexible and scalable unit for responsive design.
How rem works
- 1 rem = The font size of the root element (
<html>). - If no specific font size is set for the root element, the browser’s default is usually 16px.
For example:
- If the font size of the root element (
<html>) is 16px, then:- 1 rem = 16px
- 0.5 rem = 8px
- 2 rem = 32px
html {
font-size: 16px; /* Set root font size */
}
p {
font-size: 1.5rem; /* 1.5 times the root font size (16px) = 24px */
}
h1 {
font-size: 2rem; /* 2 times the root font size (16px) = 32px */
}
.container {
padding: 1rem; /* 16px padding */
}
Implementing rem Units
Set the root font size:
- In your
htmlelement, define the desired base font size using thefont-sizeproperty. This value will serve as the reference point for all rem units within your stylesheet. - Example:
html { font-size: 16px; }
Use rem units for font sizes:
- For all font-related properties (e.g.,
font-size,line-height,letter-spacing), use rem units to express values relative to the root font size.
Example:
h1 { font-size: 2.5rem; }
p { font-size: 1.2rem; }
Consider browser compatibility:
- While rem units are widely supported, ensure compatibility with older browsers by using a fallback font size in pixels or ems.
h1 { font-size: 2.5rem; font-size: 40px; }