CSS: Length Units

By Xah Lee. Date: . Last updated: .

Pixel unit

px

Pixel. Practically, 1/16 of default font size of a device.

Font based units (relative unit)

Line height based unit (relative unit)

rlh

line-height of the Root Element.

lh

The computed value of the line-height property of the element on which it is used.

🛑 warning: the size of actual line height may differ based on their content, e.g. contain words with large font size.

Percent (relative unit)

%

Percent. Relative to parent element. Exact meaning depends on the element it is used.

Viewport based units (relative unit)

vw vh vmin vmax lvw lvh svw svh dvw dvh vi vb

Physical units

cm mm in pt pc

Which unit to use

Use rem for any size you want to change with user's setting of font size. Including, font size, layout box widths.

For margin, padding, gap, i recommend px, because when user has larger font size, whitespace gaps between elements do not increase. See CSS: tip. Use px for margin and padding

Use viewport based sizes vw, vh etc when you want size to depend on viewport.

Use px for anything fixed. Including, for border line thickness, or border radius. CSS: Border

for percentage value, use with care, because the meaning depends on the HTML element.

Example

div {
 margin: 1rem;
}

🛑 warning: There must be no space btween the number and the CSS unit.

Unit always required (there is no default unit)

Omitting unit is syntax error, except when the value is 0.