Last updated
CSS Units Overview
CSS has two categories of units: absolute (fixed size regardless of context) and relative (size depends on parent, viewport, or font size). Relative units are preferred for responsive design because they scale with the user's settings and viewport size.
CSS Unit Reference
| Unit | Type | Relative To |
|---|---|---|
| px | Absolute | 1/96th of an inch (CSS pixel) |
| pt | Absolute | 1/72nd of an inch |
| em | Relative | Parent element's font-size |
| rem | Relative | Root element's font-size (html) |
| % | Relative | Parent element's value |
| vw | Relative | 1% of viewport width |
| vh | Relative | 1% of viewport height |
| vmin | Relative | 1% of smaller viewport dimension |
| ch | Relative | Width of "0" character in current font |
| dvh | Relative | 1% of dynamic viewport height (mobile) |
Unit Conversion Formulas
JavaScript
// px to rem (assuming 16px root font size)
const pxToRem = (px, rootFontSize = 16) => px / rootFontSize;
// rem to px
const remToPx = (rem, rootFontSize = 16) => rem * rootFontSize;
// px to em (relative to parent font size)
const pxToEm = (px, parentFontSize) => px / parentFontSize;
// px to vw (relative to viewport width)
const pxToVw = (px, viewportWidth) => (px / viewportWidth) * 100;
// pt to px
const ptToPx = (pt) => pt * (96 / 72);
console.log(pxToRem(24)); // 1.5 (rem)
console.log(remToPx(1.5)); // 24 (px)
console.log(ptToPx(12)); // 16 (px)