Resize Observer

크기 관찰자

It delivers updated element dimensions when the element resizes.

···
html
<div class="v"><header>RESIZE OBSERVER <span id="width">— px</span></header><div class="stage size"><div class="resizable" id="box"><div class="bars"><i></i><i></i><i></i></div><span id="mode">wide layout</span></div><div class="ruler"></div></div><div class="muted">container width → component layout</div></div>
css
.v{width:min(94vw,760px);height:min(88vh,320px);padding:clamp(9px,2.4vmin,18px);border:1px solid var(--line);border-radius:12px;background:var(--surface);font:500 clamp(12px,2.4vmin,16px)/1.3 var(--font-sans,system-ui,sans-serif);display:flex;flex-direction:column;gap:clamp(5px,1.4vmin,10px);overflow:hidden}.v header{display:flex;align-items:center;justify-content:space-between;gap:8px;color:var(--accent);font-weight:700}.v header span{color:var(--muted);font-weight:500}.v .stage{flex:1;min-height:0;position:relative}.v .muted{color:var(--muted)}.v .active{background:color-mix(in srgb,var(--accent) 18%,var(--surface));border-color:var(--accent)!important;color:var(--fg)}.v button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:7px;padding:5px 8px;cursor:pointer}.size{display:flex;align-items:center;justify-content:center;flex-direction:column;gap:5px}.resizable{width:75%;height:68%;border:2px solid var(--accent);border-radius:8px;background:var(--bg);display:flex;align-items:center;justify-content:center;gap:8px;animation:resize 3s ease-in-out infinite alternate}.bars{display:flex;align-items:end;gap:4px;height:35px}.bars i{display:block;width:10px;background:var(--accent);height:50%}.bars i:nth-child(2){height:100%}.bars i:nth-child(3){height:70%}.ruler{width:75%;border-top:1px dashed var(--muted)}@keyframes resize{to{width:42%}}@media(max-width:420px){.resizable{width:82%}@keyframes resize{to{width:52%}}}
js
const box=document.getElementById("box");new ResizeObserver(([entry])=>{const w=Math.round(entry.contentRect.width);document.getElementById("width").textContent=w+" px";document.getElementById("mode").textContent=w<150?"compact":"wide layout"}).observe(box)

Resize Observer watches an element rather than the viewport. A component can adapt to its available space even when only its parent panel changes size.

The demo panel resizes automatically and the measurement follows. Changing size immediately in its callback can create repeated notifications, so plan the update flow.

When to use

Use it to fit a chart or canvas to its parent container.

Open as page ↗