CSS Units
CSS lengths can be absolute (fixed on every screen) or relative (scale to font size, parent, or viewport). Picking the right one is half the layout battle.
The units you actually use
| Unit | Type | Relative to | Use it for |
|---|---|---|---|
px | Absolute | — | Borders, fine-grained tweaks. |
% | Relative | The parent's size for the same property. | Fluid widths inside a container. |
em | Relative | The element's own font-size. | Padding/margins that scale with text. |
rem | Relative | The root element's font-size. | Most modern sizing — predictable and scalable. |
vw / vh | Relative | 1% of the viewport width/height. | Hero sections, full-screen layouts. |
fr | Relative | A fraction of the remaining grid track space. | CSS Grid column/row sizing. |
ch | Relative | Width of a "0" character. | Limiting line length for readability. |
How the relative units compound
rem stays anchored to the root; em snowballs through nesting.Note: Use
em for media queries with care — many browsers ignore root-level font-size changes inside queries. Prefer em on the query itself for accessibility, but test it.Tip: A solid default:
rem for font sizes and spacing, % or fr for widths, px only for borders and hairlines.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Units</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Use the unit that means "fraction of remaining space" for the second column.
.cols { grid-template-columns: 200px 1
; }
Two letters. Stands for "fraction".
Discussion
Loading…