getComputedStyle Reads Resolved Styles
getComputedStyle returns the effective value after cascade and unit resolution, so 2em reads back as pixels, and only the inline style stays writable.
Code
// resolved styles: getComputedStyle folds em/percent units into final pixel values
const box = document.createElement("div");
box.style.fontSize = "2em";
document.body.append(box);
document.body.style.fontSize = "16px";
const styles = getComputedStyle(box);
// "2em" 在 16px 根字号下解析为 32px
console.log("font-size:", styles.fontSize);
// percentage width resolves to pixels against the parent's content box
box.style.width = "50%";
console.log("width px :", getComputedStyle(box).width);
// computed 值是只读快照:改动必须写回元素的 .style
box.style.fontSize = "24px";
console.log("inline now:", box.style.fontSize);
console.log("computed :", getComputedStyle(box).fontSize);How the snippet works
Everything operates on top-level bindings: box, styles.
Watch out for
- No third-party code is loaded at any point while this runs.
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Applying it
The file announces its steps in the output: font-size:, width px :, inline now:.
Statements that matter
const box = document.createElement("div");
document.body.style.fontSize = "16px";
const styles = getComputedStyle(box);
Interactive Tools for This Topic
Aspect Ratio CalculatorSimplify a width-to-height ratio, show its decimal value, and derive a matching height for a new width.Border Radius PreviewPreview four-corner border-radius values on a live box and copy the generated shorthand border-radius CSS declaration.Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.
FAQ
- Does getComputedStyle Reads Resolved Styles run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.