Usage
import { resolveCssSize } from 'ngwr/utils';
resolveCssSize(48); // { cssValue: '48px', pxValue: 48 }
resolveCssSize('3rem'); // { cssValue: '3rem', pxValue: 3 * rootFont }
resolveCssSize('80%'); // { cssValue: '80%', pxValue: null }
resolveCssSize(null, { defaultValue: '6rem' }); // falls backWhy ngwr provides this
Components that accept a size input often need both a CSS string (for width: / height:) AND a pixel number (for canvas math, ResizeObserver thresholds, intersection-observer roots). Parsing '3rem' to px, handling null defaults, supporting % / vh / em — the same 15 lines end up duplicated across every component that takes a size input.
// Native — you need to handle every shape yourself.
function pxForCss(raw: number | string | null): number | null {
if (raw == null) return null;
if (typeof raw === 'number') return raw;
if (raw.endsWith('px')) return parseFloat(raw);
if (raw.endsWith('rem')) {
const root = parseFloat(getComputedStyle(document.documentElement).fontSize);
return parseFloat(raw) * root;
}
return null; // '%', 'vh', 'em', … ignored — bug surface
}
// ngwr — one call, returns both the CSS value and the px equivalent.
const { cssValue, pxValue } = resolveCssSize(raw);API
| Name | Description | Type | Default |
|---|---|---|---|
resolveCssSize(raw, options?) | Resolves number / "12px" / "3rem" / "80%" to a CSS value + pixel equivalent (when computable). | (raw, options?) => ResolvedCssSize | — |
ResolvedCssSize | Return shape: { cssValue: string; pxValue: number | null }. | interface | — |
ResolveCssSizeOptions | { defaultValue?: unknown } — used when raw is null/undefined. | interface | — |