23. Relative Units: Em, Rem, and Viewport Units
These units are crucial for building accessible and truly responsive websites.
3. Em (em)
The em unit is relative to the font size of the element itself. If used on a font-size property, it is relative to the parent's font size.
- If the parent font size is 16px, then
1em= 16px. - If the element's font size is set to 20px, then
1emused for padding on that element is 20px.
The Problem (Compounding): em units can compound. If a parent is 1.5em (24px) and a child is also 1.5em, the child becomes 36px, leading to unpredictable sizing.
4. Rem (rem - Root Em)
The rem unit is relative only to the font size of the root HTML element (<html>). This solves the compounding problem of em.
- By default,
1rem= 16px (browser default). - If a user changes the default browser font size, all
remunits scale proportionally, ensuring excellent accessibility.
Best Practice: Use rem for font sizes and spacing (padding, margin) to ensure everything scales uniformly.
5. Viewport Units (vw, vh)
Viewport units are relative to the size of the browser window (the viewport).
vw(Viewport Width): 1vw is 1% of the viewport width.vh(Viewport Height): 1vh is 1% of the viewport height.vmin,vmax: Based on the smaller or larger dimension of the viewport.
css /* The text size will scale smoothly as the browser window is resized */ .responsive-title { font-size: 5vw; }
/* A banner that is always 70% of the screen height */ .tall-banner { height: 70vh; }