Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

CSS length units define distances such as `16px`, `1.25rem`, `50vw`, and `2cqi`. Use `rem` for root-scaled typography and spacing, `em` for component-local scaling, `px` for precise details, `%` for containing-box relationships, viewport units for window-sized layouts, and container units for reusable components.

Key takeaways

  • A CSS length is a number immediately followed by a unit, except that unitless zero is valid: `0`.
  • `rem` follows the root font size, while `em` follows an element’s local font-size context and can compound when nested.
  • `px` means a CSS pixel, not necessarily one physical device pixel; fixed CSS pixels are useful for borders and fine visual details.
  • `svh`, `lvh`, and `dvh` express different mobile viewport-height behaviors, so `100vh` is not always the currently visible mobile height.
  • Container units such as `cqi` respond to an eligible query container instead of the browser viewport.
  • `clamp()`, `min()`, `max()`, and `calc()` allow fluid values without letting typography or layout become unusably small or large.

What are CSS length units?

CSS length units represent distances used by properties such as `width`, `height`, `margin`, `padding`, `border-width`, `font-size`, and `text-shadow`. A length can be based on a CSS pixel, font metric, viewport, containing block, or query container; a CSS length is not necessarily a literal measurement in physical screen pixels. The MDN `` reference documents the current syntax and unit families.

.card {
  width: 24rem;
  padding: 1.5rem;
  border-width: 1px;
}

The number and unit must have no intervening space. Unitless zero is the main exception:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Declaration Result
width: 20rem; Valid length
width: 0; Valid unitless zero
width: 20 rem; Invalid because the number and unit are separated
width: 20; Normally invalid because a nonzero length unit is missing

Decimal values such as `0.5px` may be valid, and negative lengths may be valid for some properties but prohibited for others. Whether a length is accepted depends on the property’s grammar and the layout context.

Popular on Amazon
Sale
Rena Chris Architectural Scale Ruler: 12" Imperial Aluminum Alloy Metal Architecture Measuring Tools, Engineering Drafting Construction Drawing Blueprints Triangular Architect Scaling Rulers 12 Inches
  • 12" triangular architect scale designed to facilitate the drafting and measuring of architectural drawings, such as floor plans, blue Prints, and orthographic projections
  • Triangular ruler features 3 sides with 6 different scales, and made from high Impact aluminum, build to last
  • Laser etched scales never fading. Architect ruler with enduring laser cut imperial prints for accuracy. They will not wipe or scratch off ever
  • Professional grade for accuracy color coded triangular scale for easy and quick selection of the desired scale
  • Standard imperial measurements: 1-1/2, 1, 3/4, 3/8, 3/16, 3/32, 1/2, 1/4, 1/8, 3, 16

How should you choose a CSS length unit?

Choose the reference frame that should control the value. Ask whether the value should respond to the root font, local text, parent or containing block, viewport, query container, or fixed output medium.

Design need Good starting point Reason
Body and heading typography rem Scales from the root font size and avoids most nested compounding
Spacing tokens and gaps rem Provides a predictable root-based scale
Component padding tied to its text em Grows with the component’s local typography
Paragraph reading width ch Approximates the active font’s text measure
Width related to a containing box %, auto, grid, or flex sizing Expresses a relationship to available layout space
Borders and small visual offsets px Offers precise visual control
Viewport-sized hero or backdrop vw, vh, or logical viewport units Responds to the browser viewport
Mobile full-height panel svh, dvh, or a tested combination Accounts for changing browser controls
Reusable card or widget cqi, cqw, or related container units Responds to the component’s actual container
Fluid but bounded type clamp() with rem, vw, or cqi Combines flexibility with minimum and maximum limits
Print dimensions mm, cm, in, pt, pc, or Q Matches fixed-output workflows more naturally

What is the difference between absolute and relative CSS units?

Absolute CSS units use a fixed CSS reference system, while relative CSS units resolve against another value such as a font size, viewport dimension, or query-container dimension. Relative units do not all mean “relative to the parent”: each unit has its own reference frame, and percentages can resolve differently depending on the property.

What are the absolute CSS length units?

Absolute units are most useful when the output or visual detail should use a fixed reference. The CSS Values specification defines the unit relationships, while the MDN numeric data types reference provides the practical conversion table.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Unit Meaning Common use
px CSS pixel Borders, icons, small offsets, controlled visual details
cm Centimeter Print and fixed physical output
mm Millimeter Print and physical dimensions
Q Quarter-millimeter Specialized print layouts
in Inch Print
pt Point; 1pt = 1/72in Print and legacy typography
pc Pica; 1pc = 1/6in Print and legacy typography

CSS defines `1in` as `96px`, `1cm` as `96px / 2.54`, `1pt` as `1/72in`, `1pc` as `1/6in`, and `1Q` as `1/40cm`. Those relationships describe CSS’s reference system; they do not guarantee that a monitor will render a physically measured inch or centimeter. Physical units are most dependable for print and other fixed-output media.

Is a CSS pixel the same as a device pixel?

No. A CSS `px` is a CSS pixel, not necessarily one physical pixel on a display. Browsers adapt CSS pixels to viewing conditions and device pixel density. A one-pixel border can therefore be a deliberate rendering detail without implying a physically measured pixel.

.button {
  border: 1px solid;
  padding: 0.75rem 1rem;
}

Using `px` is not automatically an accessibility failure. The problem is usually a rigid layout that prevents text from scaling, wrapping, or growing. Use fixed pixels for intentional visual details, but avoid fixed-height text containers and test zoom and larger default fonts.

How does em work in CSS?

`em` is based on the computed `font-size` of the element for most properties. When `em` is used on the element’s own `font-size`, the value is based on the inherited font size. After the element’s font size is computed, padding, margins, and other `em`-based dimensions on that element use the element’s computed font size.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.parent {
  font-size: 20px;
}

.child {
  font-size: 1.2em; /* 24px when inherited size is 20px */
  padding: 1em;     /* based on the child's computed font size */
}

`em` is useful when a component should scale as a unit. A button’s padding, badge spacing, border radius, or icon gap can grow with the button’s text.

Nested `em` values can compound:

ul {
  font-size: 1.2em;
}

ul ul {
  font-size: 1.2em;
}

Each nested list applies another multiplication to the inherited font size. Deliberate local scaling is a good reason to use `em`; a global spacing system is often easier to predict with `rem`.

How does rem work in CSS?

`rem` is relative to the computed font size of the root element, normally ``. Root-relative units also include `rex`, `rcap`, `rch`, `ric`, and `rlh`, which use root-level font metrics.

Also popular on Amazon
Sale
Pacific Arc 12 inch Pica Pole Metal Ruler, with Pica, Points, Inches, and Agate Measurements, Stainless Steel Ruler for Drafting
  • FOUR SCALES ON ONE RULER - The Pacific Arc pica pole carries pica, point, agate and inch graduations on a single stainless steel ruler, so you can measure type, leading, column depth and artwork without switching tools.
  • ETCHED GRADUATIONS THAT LAST - The scale marks are etched into the stainless steel rather than printed on, so they hold up to handling, solvents and daily desk use instead of wearing away at the edges.
  • BUILT FOR PRINT AND LAYOUT WORK - Also called a line gauge, pica stick, printer ruler or agate ruler. Used by printers, typesetters, editors, graphic designers, sign makers, drafters and design students for proofs, mock-ups and layouts.
  • CHOOSE YOUR LENGTH AND STYLE - Available in several lengths and in single or multi-pack quantities, in both the hooked-end profile and a flat profile with a hanging hole. Select the option that matches your desk and your work.
  • A DURABLE METAL STRAIGHT EDGE - The stainless steel body resists nicks and bending, so the ruler doubles as a reliable straight edge for trimming, ruling and marking. A practical gift for a printer, editor or designer.
html {
  font-size: 100%;
}

.page {
  padding: 2rem;
}

h1 {
  font-size: 2.5rem;
}

`rem` is a strong default for typography, spacing, gaps, radii, and design tokens when those values should follow the root text scale. `rem` avoids most nested `em` compounding and responds when the root font size changes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not assume that `1rem` always equals `16px`. `1rem` equals the computed root font size; 16 CSS pixels is only a common default. Setting `html { font-size: 62.5%; }` to make `1rem` appear to equal `10px` is optional and can make root-size assumptions harder to understand. A design should not depend on users retaining a particular default font size.

What are font-relative and line-metric units?

Font-relative units use measurements from the current or root font. They are valuable for typography, text measure, alignment, and vertical rhythm, but font family, font loading, language, weight, and fallback fonts can change the result.

Unit Reference Suitable use
ch Advance measure of the active font’s 0 glyph Approximate paragraph measure and input widths
ex x-height of the current font Specialized typographic alignment
cap Cap height of the current font Alignment related to capital-letter height
ic Advance measure of the CJK 水 glyph CJK-aware sizing
lh Computed line-height of the element Vertical rhythm tied to local line height
rch, rex, rcap, ric, rlh The corresponding metric from the root element’s font Root-based typographic systems

`ch` does not mean the width of an arbitrary character. A `60ch` paragraph is an approximate font-dependent measure based on the active font’s zero glyph, not a promise that every line contains exactly 60 characters.

.article {
  max-width: 65ch;
  line-height: 1.6;
}

.article-section {
  margin-block: 2lh;
}

`lh` follows the theoretical computed line height. Actual line boxes can still vary because of content and font metrics, so use `lh` as a rhythm tool rather than a guarantee about the exact painted height of every line.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do percentages work compared with CSS length units?

Percentages are technically a separate CSS value type, even though many properties accept a combined `` value. A percentage’s reference depends on the property, containing block, writing mode, and layout algorithm.

.box {
  width: 50%;
  padding: 10%;
  margin-top: 10%;
}

`width: 50%` commonly relates to the containing block, but it is unsafe to describe every percentage as simply “a percentage of the parent.” Padding and margins follow their own percentage-resolution rules, and the relevant containing context can be non-obvious. Verify the property when an apparently reasonable percentage produces an unexpected layout.

What are viewport CSS length units?

Viewport units resolve against the browser viewport. Standard units include `vw` for 1% of viewport width, `vh` for 1% of viewport height, `vmin` for 1% of the smaller viewport dimension, and `vmax` for 1% of the larger dimension.

Unit Reference Example use
vw 1% of viewport width Viewport-width padding or fluid type
vh 1% of viewport height Viewport-driven compositions
vmin 1% of the smaller viewport dimension Scale that should fit within either axis
vmax 1% of the larger viewport dimension Scale based on the dominant viewport axis
vi 1% of the viewport’s inline dimension Writing-mode-aware inline sizing
vb 1% of the viewport’s block dimension Writing-mode-aware block sizing

Logical viewport units such as `vi` and `vb` follow the inline and block axes instead of assuming horizontal width and vertical height. Logical units pair well with logical properties such as `padding-inline`, especially in right-to-left, vertical-writing, and internationalized layouts.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.hero {
  min-height: 100vh;
  padding-inline: 5vw;
}

.internationalized-panel {
  padding-inline: 4vi;
  min-block-size: 80vb;
}

Why can 100vh clip content on mobile?

`100vh` can be taller than the currently visible mobile area when browser interface controls are expanded. Browser controls can retract and reappear as the user scrolls, and current implementations map default viewport units such as `vh` to the large viewport behavior described in the MDN viewport-unit documentation. Content inside a hard `height: 100vh` panel can therefore extend beneath browser controls.

Also popular on Amazon
Mr. Pen- Metal Straight Edge Ruler, 4 pcs, 6", 8", 12", 14" | Stainless Steel Ruler Set, Imperial & Metric Measurements for Drawing, Home, Office, Engineering
  • The Set Includes 4 Steel Rulers In 4 Different Sizes: 14 Inch, 12 Inch, 8 Inch And 6 Inch
  • Made From High Impact 1/32 Inch (0.9mm) Thick Stainless Steel
  • Inch And cm Measurements, Etched With Marking Up To 1/64 Inch Measurements And 1/20 Centimeter Measurements
  • Inch To mm Conversion Table In The Back Of The Rulers
  • Accurate Markings, Perfect For Schools, Offices, Home Schools, Architects, And Engineers
.modal {
  height: 100vh;
}

/* Potentially safer starting point */
.modal {
  min-height: 100svh;
}

What is the difference between svh, lvh, and dvh?

`svh`, `lvh`, and `dvh` represent small, large, and dynamic viewport heights. The three families also exist for width, inline, block, minimum, and maximum dimensions.

Family Meaning Typical choice Main trade-off
sv* Small viewport, assuming browser UI is expanded Content that must remain visible with controls present May leave unused space after controls retract
lv* Large viewport, assuming browser UI is retracted Maximum immersive space May extend behind visible browser UI
dv* Dynamic viewport that changes with browser UI Layouts that should track the current viewport Can resize and relayout while controls move
.fullscreen-panel {
  min-height: 100svh;
}

.interactive-hero {
  min-height: 100dvh;
}

`svh` is a safer starting point when important content must remain visible while mobile browser controls are present. `dvh` tracks the changing viewport and may suit an interactive full-screen application, but dynamic resizing can be visually disruptive. `lvh` maximizes available space but can place content behind visible browser UI. Test the target browsers and prefer flexible content over assuming one unit is universally correct.

What are container query length units?

Container query length units size descendants relative to an eligible query container rather than the entire viewport. Container units are useful when a component can appear in a sidebar, grid column, modal, or full-width region and should adapt to its actual available space.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Unit Reference
cqw 1% of the query container’s width
cqh 1% of the query container’s height
cqi 1% of the query container’s inline size
cqb 1% of the query container’s block size
cqmin The smaller of cqi and cqb
cqmax The larger of cqi and cqb

Establish the container before using container units. `container-type: inline-size` is generally the least restrictive option when a component only needs to respond to inline size.

.card-grid {
  container-type: inline-size;
}

.card h2 {
  font-size: clamp(1.1rem, 1rem + 2cqi, 2rem);
}

The MDN container-query guide explains container units and query-container setup. `container-type: size` queries both inline and block dimensions and applies size containment; `inline-size` applies inline-size containment. A size container needs a usable size from its layout context or an explicit size, otherwise containment can cause unexpected collapse.

If no eligible query container exists, container query length units fall back to the small viewport unit for the relevant axis. That fallback can make a component unexpectedly large or small, so inspect the container configuration whenever `cqi` or another container unit behaves like a viewport unit.

How do calc, min, max, and clamp combine CSS units?

CSS math functions combine compatible values so a design can be fluid without losing usable boundaries. `calc()` performs arithmetic, `min()` selects the smallest result, `max()` selects the largest result, and `clamp(minimum, preferred, maximum)` constrains a preferred fluid value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.page-title {
  font-size: clamp(1.75rem, 1rem + 3vw, 4rem);
}

.content {
  width: min(100% - 2rem, 70ch);
}

.sidebar {
  padding: max(1rem, 3vw);
}

Mixed units are often the purpose of these functions: a viewport or container term supplies fluid scaling, while `rem` values provide readable lower and upper limits. A percentage may remain unresolved until layout, and a syntactically valid expression can still be unsuitable for a particular containing context. Check both the CSS grammar and the resulting layout.

Which CSS length unit should you use for common tasks?

Typography

Start with `rem` for body text and headings when typography should follow the root text scale. Use `em` when the typography and internal dimensions of one component should scale together. Use bounded fluid type when a heading should respond to available space.

body {
  font-size: 1rem;
}

h1 {
  font-size: clamp(2rem, 1.25rem + 3vw, 4rem);
}

Spacing and component internals

Use `rem` for shared spacing tokens and predictable gaps. Use `em` for a self-contained button, badge, or label whose padding should grow with its own text. Use `%` when the intended relationship is to a containing block rather than to typography.

Also popular on Amazon
Pacific Arc 18 inch Pica Pole Metal Ruler, with Pica, Points, Inches, and Agate Measurements, Stainless Steel Ruler for Drafting
  • FOUR SCALES ON ONE RULER - The Pacific Arc pica pole carries pica, point, agate and inch graduations on a single stainless steel ruler, so you can measure type, leading, column depth and artwork without switching tools.
  • ETCHED GRADUATIONS THAT LAST - The scale marks are etched into the stainless steel rather than printed on, so they hold up to handling, solvents and daily desk use instead of wearing away at the edges.
  • BUILT FOR PRINT AND LAYOUT WORK - Also called a line gauge, pica stick, printer ruler or agate ruler. Used by printers, typesetters, editors, graphic designers, sign makers, drafters and design students for proofs, mock-ups and layouts.
  • CHOOSE YOUR LENGTH AND STYLE - Available in several lengths and in single or multi-pack quantities, in both the hooked-end profile and a flat profile with a hanging hole. Select the option that matches your desk and your work.
  • A DURABLE METAL STRAIGHT EDGE - The stainless steel body resists nicks and bending, so the ruler doubles as a reliable straight edge for trimming, ruling and marking. A practical gift for a printer, editor or designer.

Text measure

Use `max-width: 60ch` or `max-width: 65ch` as an approximate reading measure. Test the actual font, language, weight, and fallback behavior because `ch` is based on the active font’s zero glyph, not a character counter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Viewport compositions

Use `vw`, `vh`, `vmin`, `vmax`, `vi`, or `vb` only when the browser viewport should control the design. Use the small, large, or dynamic variants when mobile browser chrome changes the meaning of “full screen.”

Reusable components

Use container units when the component should respond to its card, column, modal, or other local container. Viewport width is a poor proxy for a component’s available width when the same component appears in several layout contexts.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do accessibility and responsive layouts affect unit choice?

Accessible CSS does not require avoiding `px` completely. Accessible layout requires that text can scale, content can wrap, boxes can grow, and zoom or larger user font settings do not hide information.

  • Prefer `min-height` for sections containing text when content may grow.
  • Avoid putting text in a rigid fixed-height box unless clipping is intentional.
  • Test browser zoom and increased default font size.
  • Test narrow screens, long translations, right-to-left text, vertical writing where relevant, and fallback fonts.
  • Treat `overflow: hidden` as a possible symptom-hiding workaround rather than an automatic fix.
  • Use root-relative or font-relative units when a value should scale with text.
/* More resilient for content that can grow */
.panel {
  min-height: 20rem;
}

/* Risky when content may exceed the fixed height */
.panel {
  height: 20rem;
  overflow: hidden;
}

Why do computed CSS values sometimes show pixels or fractional values?

A specified length can resolve to a computed absolute length, and the original unit identity is not retained in the computed value. The CSS Values and Units specification describes canonical serialization in pixels.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Layout can use fractional CSS pixels. Browsers may distribute or round those values differently at painted edges, and some border or outline rendering can round computed lengths to device pixels. A `0.5px` border can therefore look different depending on the browser and device pixel ratio. Apparent one-pixel discrepancies are not necessarily evidence that the CSS calculation failed.

What is not a CSS length unit?

CSS has many numeric unit types that are not lengths. The MDN values-and-units guide distinguishes these categories.

Value or unit Category Example
% Percentage, not technically a <length> width: 50%;
fr Flexible grid track unit grid-template-columns: 1fr 2fr;
deg, rad, turn Angle units rotate: 45deg;
s, ms Time units transition-duration: 200ms;
dpi, dpcm, dppx Resolution units resolution: 2dppx;
Hz, kHz Frequency units Audio-related CSS values
16/9 Ratio value aspect-ratio: 16 / 9;

CSS length units reference

Family Units Reference frame
Absolute px, cm, mm, Q, in, pt, pc CSS fixed reference system or output medium
Local font em, ex, cap, ch, ic, lh Element’s font or line metrics
Root font rem, rex, rcap, rch, ric, rlh Root element’s font or line metrics
Viewport vw, vh, vmin, vmax, vi, vb Browser viewport
Small viewport svw, svh, svmin, svmax, svi, svb Viewport with browser UI expanded
Large viewport lvw, lvh, lvmin, lvmax, lvi, lvb Viewport with browser UI retracted
Dynamic viewport dvw, dvh, dvmin, dvmax, dvi, dvb Current viewport as browser UI changes
Container cqw, cqh, cqmin, cqmax, cqi, cqb Eligible query container

A practical CSS length debugging checklist

  1. Identify the reference frame: root font, local font, containing block, viewport, query container, or fixed output.
  2. Inspect the computed style, not only the declaration in the stylesheet.
  3. Check whether the element’s font, root font, writing mode, or fallback font changes the reference value.
  4. For percentages, check the specific property’s percentage-resolution rules.
  5. For `em`, inspect ancestors for compounding font-size declarations.
  6. For container units, confirm that an ancestor has the necessary `container-type` and a usable size.
  7. For mobile full-height layouts, compare `svh`, `lvh`, and `dvh` behavior on the target browser.
  8. Test zoom, large text, long content, translations, and narrow widths before fixing overflow with clipping.

Frequently Asked Questions

Is 1rem always equal to 16px?

No. `1rem` equals the computed font size of the root element, normally ``. It commonly works out to 16 CSS pixels when the browser’s default root font size is used, but user settings and author CSS can change the value.

Should CSS use rem instead of px everywhere?

No. Use `rem` when a value should follow the root text scale, but use `px` for intentional borders and fine visual details, `em` for component-local scaling, viewport units for viewport compositions, and container units for components that respond to their local container.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What should replace 100vh on mobile?

There is no universal replacement. Use `100svh` when important content must remain visible with browser controls expanded, `100dvh` when the layout should track the current viewport, or a tested combination. `dvh` can resize during browser-interface transitions, while `lvh` can extend behind visible browser UI.

Why is my cqi value unexpectedly large or small?

Container query units require an eligible query container. Establish one with a suitable `container-type`, such as `container-type: inline-size`; without an eligible container, container units fall back to small viewport units for the relevant axis.

The Bottom Line

The best CSS length unit is the one whose reference frame matches the design decision. Use rem for root-scaled type and spacing, em for local component scaling, px for precise details, percentages for containing-box relationships, viewport units for window-driven compositions, and container units for reusable components. Add clamp(), min(), or max() when fluid sizing needs safe limits.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.