getBoundingClientRect Measures Rendered Boxes
getBoundingClientRect returns the rendered box in viewport coordinates including padding and border, the primitive for tooltips and droppables.
Code
// getBoundingClientRect 返回元素在视口坐标系的渲染盒(含边框)
const box = document.createElement('div');
box.style.position = 'fixed';
box.style.left = '40px';
box.style.top = '60px';
box.style.width = '120px';
box.style.height = '48px';
box.style.padding = '8px';
box.style.border = '2px solid black';
document.body.append(box);
const rect = box.getBoundingClientRect();
console.log('x/y:', rect.x, rect.y);
console.log('width includes padding+border:', rect.width);
console.log('height:', rect.height);
// top 是视口坐标:普通文档流元素随滚动变化,本示例用 position: fixed 就是为了让坐标在滚动下保持稳定
console.log('top in viewport:', rect.top);
// 批量读取一次、再统一写入:读写交错会强制多次重排
const measured = box.getBoundingClientRect().width;
box.style.width = '200px';
console.log('measured before write:', measured);Inside the snippet
Top-level bindings box, rect, measured hold the demo state — nothing sits inside a function scope.
What to watch for
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Putting it to use
The run emits 5 labeled sections — x/y:, width includes padding+border:, height:, top in viewport:, measured before write: — one per step.
Core lines
const measured = box.getBoundingClientRect().width;
const box = document.createElement('div');
const rect = box.getBoundingClientRect();
Interactive Tools for This Topic
CSS Flexbox PlaygroundInteractively test CSS flexbox container and item properties with a live preview. Adjust justify-content, align-items, flex-direction, and flex-grow to see layout changes.CSS Grid PlaygroundExperiment with CSS grid layout properties interactively. Define columns, rows, gaps, and areas while watching the grid template update in a live visual preview.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does getBoundingClientRect Measures Rendered Boxes 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.