iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

UnitTypeRelative toUse it for
pxAbsoluteBorders, fine-grained tweaks.
%RelativeThe parent's size for the same property.Fluid widths inside a container.
emRelativeThe element's own font-size.Padding/margins that scale with text.
remRelativeThe root element's font-size.Most modern sizing — predictable and scalable.
vw / vhRelative1% of the viewport width/height.Hero sections, full-screen layouts.
frRelativeA fraction of the remaining grid track space.CSS Grid column/row sizing.
chRelativeWidth of a "0" character.Limiting line length for readability.

How the relative units compound

html { font-size: 16px } — sets the root .parent { font-size: 1.5rem; } ← 24px 1.5rem always means 1.5 × root (16px) = 24px .child { font-size: 1.5em; } ← 36px 1.5em means 1.5 × parent's font-size (24px) = 36px em compounds; rem does not.
Fig 1. 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 &raquo;</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 ; }

Test yourself

Q1. Which unit is relative to the root element's font size?
Q2. What does `50vh` mean?
Q3. Which unit is best for media-query breakpoints?

Discussion

Loading…