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.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// 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

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.