
Responsive web development requires websites to adapt to different screen sizes, devices and layouts. CSS media queries help developers adjust designs according to viewport dimensions, but they cannot always respond to changes affecting an individual component.
Consider a dashboard containing multiple cards. When a sidebar opens, the available width of a chart decreases. The browser window itself might not change size, but the chart container does. A traditional window resize event may not detect this particular change.
The Resize Observer API solves this problem by allowing JavaScript to monitor changes in the dimensions of individual HTML elements.
Developers can use it to build adaptive charts, responsive components, dynamic interfaces, resizable panels and other applications that depend on element dimensions.
This guide explains how Resize Observer works, its important methods, implementation techniques, React integration, practical projects and common development challenges.
The Resize Observer API is a browser technology that allows JavaScript to detect changes in the size of an element's content box or border box.
Its main interface is:
ResizeObserver
Developers create an observer, specify which elements should be monitored and provide a callback function. Whenever an observed element changes size, the browser delivers information about the updated dimensions.
For example:
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
console.log("Element width:", entry.contentRect.width);
console.log("Element height:", entry.contentRect.height);
}
});
const element = document.querySelector(".container");
observer.observe(element);
In this example, the browser monitors the selected container. When its size changes, the callback receives information about the new dimensions.
Unlike the window resize event, Resize Observer can detect element-level size changes caused by layout changes, parent elements, content changes and other factors.
Modern applications contain components that can change dimensions independently of the browser window.
Examples include:
Dashboard cards.
Resizable sidebars.
Data visualisation components.
Image containers.
Expandable navigation panels.
Dynamic forms.
Embedded widgets.
Responsive charts.
Split-screen interfaces.
Without Resize Observer, developers may need to combine window resize events, repeated measurements and additional event handling to detect these changes.
Resize Observer provides a dedicated mechanism for observing element dimensions.
Its major advantages include:
Element-level monitoring: It detects changes to individual elements instead of monitoring only the browser viewport.
Efficient notifications: The browser manages resize observation and delivers updates when relevant size changes occur.
Multiple element observation: One observer can monitor several elements.
Framework compatibility: It can be integrated with React, Vue, Angular and other JavaScript frameworks.
Dynamic interfaces: It helps applications respond to layout changes caused by content, panels and component interactions.
Resize Observer follows a straightforward process.
Developers create an instance using the ResizeObserver constructor.
const observer = new ResizeObserver(callback);
The callback receives an array of ResizeObserverEntry objects.
The application identifies the element whose dimensions need to be monitored.
const box = document.querySelector(".box");
The observe() method registers the selected element.
observer.observe(box);
Whenever an observed element's relevant dimensions change, the browser invokes the callback.
const observer = new ResizeObserver((entries) => {
entries.forEach((entry) => {
console.log(entry.target);
console.log(entry.contentRect.width);
});
});
When observation is no longer necessary, developers can stop monitoring an individual element or disconnect the observer completely.
observer.unobserve(box);
// Stop observing all registered elements
observer.disconnect();
Disconnecting observers is important in applications that dynamically create and remove components.
The ResizeObserver interface creates an observer that monitors element dimensions.
const resizeObserver = new ResizeObserver((entries, observer) => {
console.log("Size updated");
});
The callback receives two arguments:
entries: An array of resize observation entries.
observer: The ResizeObserver instance that triggered the callback.
Each ResizeObserverEntry represents an observed element and provides information about its dimensions.
Important properties include:
target: The observed element.
contentRect: A legacy-compatible rectangle containing content dimensions.
contentBoxSize: Information about the content box size.
borderBoxSize: Information about the border box size.
devicePixelContentBoxSize: Content dimensions expressed in device pixels.
ResizeObserverSize provides logical dimensions through two properties:
inlineSize: The size along the inline axis.
blockSize: The size along the block axis.
In common horizontal writing modes, inlineSize corresponds to width and blockSize corresponds to height. Their meaning changes with writing direction.
One important feature of Resize Observer is that developers can choose which box model they want to monitor.
The content box represents the area available for the element's actual content.
It excludes padding and borders.
observer.observe(element, {
box: "content-box"
});
This is the default observation mode.
It is useful when an application needs to respond to changes in the space available for text, images or other content.
The border box includes the content, padding and border.
observer.observe(element, {
box: "border-box"
});
This is useful when the complete visible element dimensions are important.
The device-pixel content box reports the content dimensions in device pixels before CSS transforms are applied to the element or its ancestors.
observer.observe(element, {
box: "device-pixel-content-box"
});
This can be useful for graphics applications, canvas rendering and high-resolution visual output.
Support for individual observation options should be checked against the browsers targeted by an application.
The observe() method starts monitoring an element.
observer.observe(element);
It also accepts an optional configuration object.
observer.observe(element, {
box: "border-box"
});
An observer can monitor multiple elements by calling observe() for each target.
The unobserve() method stops monitoring a specific element without disconnecting the observer from other elements.
observer.unobserve(element);
This is useful when a component is removed or no longer needs size monitoring.
The disconnect() method stops monitoring all elements registered with that observer.
observer.disconnect();
It is commonly used during component cleanup.
A simple project can demonstrate how an interface changes when its container becomes wider or narrower.
<div class="wrapper">
<div class="resize-box">
<h2>Responsive Component</h2>
<p id="dimensions">Waiting for size changes...</p>
</div>
</div>
.wrapper {
width: 80%;
max-width: 800px;
resize: horizontal;
overflow: auto;
border: 2px solid #999;
padding: 15px;
}
.resize-box {
width: 100%;
padding: 20px;
box-sizing: border-box;
background: #e7f0ff;
}
.resize-box h2 {
font-size: 22px;
}
#dimensions {
font-size: 14px;
}
const box = document.querySelector(".resize-box");
const dimensions = document.querySelector("#dimensions");
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const width = entry.contentRect.width;
const height = entry.contentRect.height;
dimensions.textContent =
`Width: ${width.toFixed(1)}px | Height: ${height.toFixed(1)}px`;
if (width < 400) {
box.style.background = "#fff0d9";
} else {
box.style.background = "#e7f0ff";
}
}
});
observer.observe(box);
When the wrapper is resized, the observed component receives new dimensions. The JavaScript callback updates the displayed measurements and background colour.
This example demonstrates element-level responsiveness without relying on a browser window resize event.
React developers frequently build components that must respond to changes in their parent containers.
For example, a chart may need to adjust its layout when a dashboard panel becomes narrower.
A custom hook can make Resize Observer reusable.
import { useEffect, useRef, useState } from "react";
function useElementSize() {
const elementRef = useRef(null);
const [size, setSize] = useState({
width: 0,
height: 0
});
useEffect(() => {
const element = elementRef.current;
if (!element || !("ResizeObserver" in window)) {
return;
}
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
setSize({
width: entry.contentRect.width,
height: entry.contentRect.height
});
}
});
observer.observe(element);
return () => {
observer.disconnect();
};
}, []);
return { elementRef, size };
}
function ResponsivePanel() {
const { elementRef, size } = useElementSize();
return (
<div ref={elementRef} className="panel">
<h2>Responsive Panel</h2>
<p>Width: {size.width.toFixed(0)}px</p>
<p>Height: {size.height.toFixed(0)}px</p>
</div>
);
}
export default ResponsivePanel;
This implementation:
Uses useRef to access the DOM element.
Uses useState to store the latest dimensions.
Creates the observer inside useEffect.
Updates component state when dimensions change.
Disconnects the observer during cleanup.
For server-rendered React applications, browser APIs should only be accessed in client-side execution.
Charts and graphs often need to adjust their dimensions according to the available container space.
A chart designed for a wide dashboard may become difficult to read when displayed in a narrow panel.
Resize Observer can detect the available dimensions and notify a chart library when it should recalculate its layout.
A simplified example is:
const chartContainer = document.querySelector(".chart-container");
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const width = entry.contentRect.width;
const height = entry.contentRect.height;
updateChartDimensions(width, height);
}
});
observer.observe(chartContainer);
The updateChartDimensions() function represents application-specific chart resizing logic.
Developers can use this approach with charting libraries, custom SVG visualisations and canvas-based applications.
The window resize event detects changes in the browser window's dimensions.
Resize Observer detects changes in the dimensions of individual elements.
For example, opening a sidebar can reduce a dashboard card's width without changing the browser window size.
A window resize listener may not detect this layout change, whereas Resize Observer can detect the card's new dimensions.
Both techniques have useful applications:
Use the window resize event when application behaviour depends on viewport dimensions.
Use Resize Observer when behaviour depends on an individual element's dimensions.
Use both when an application needs to respond to viewport and component-level changes.
CSS container queries allow styles to change according to the dimensions or characteristics of a container.
Resize Observer provides JavaScript notifications when element dimensions change.
For example:
Use container queries to change the layout of a card using CSS.
Use Resize Observer to update a chart's JavaScript configuration.
Use Resize Observer when application logic depends on the measured dimensions.
Use both when visual styling and JavaScript behaviour need coordinated responsiveness.
CSS container queries are generally simpler for styling-only requirements. JavaScript observation is more appropriate when code needs to respond to size changes.
Dashboard components can adjust their visualisation, text and layout when users resize panels or open sidebars.
Charts can recalculate dimensions when their containers change size.
Navigation components can change their behaviour when the available space becomes smaller.
Applications can respond to changes in image containers and adjust rendering or display behaviour.
Third-party widgets can adapt to the space allocated by the page that contains them.
Code editors, document editors and design tools can respond to changes in their surrounding panels.
Applications can adjust text presentation according to component dimensions when CSS alone is not sufficient for the required behaviour.
A common problem occurs when an observer callback changes the dimensions of the same element being observed.
For example, the callback may increase an element's width every time it detects a width change.
This can create repeated resize notifications.
To avoid this:
Do not make unnecessary dimension changes inside callbacks.
Check whether the desired dimensions have already been applied.
Use stable layout rules.
Separate measurement and rendering logic when necessary.
In React applications, frequent dimension updates can trigger repeated rendering.
Developers should avoid updating state when the measured values have not meaningfully changed.
For complex applications, they can also consolidate updates or use carefully designed scheduling strategies.
Observers should be disconnected when their components are no longer needed.
Failure to manage observer lifecycles can lead to unnecessary work and resource retention.
The content box and border box represent different measurements.
Choosing the wrong box can produce incorrect calculations.
Always select the observation mode according to the actual requirement.
Older browsers and restricted execution environments may not provide Resize Observer.
Applications should check availability and provide an appropriate fallback where necessary.
Changing an observed element's dimensions can trigger additional layout calculations.
Complex feedback between observed dimensions and applied styles should be avoided.
Developers should follow these recommendations:
Create observers only when size monitoring is required.
Observe only relevant elements.
Disconnect observers during component cleanup.
Use unobserve() when an individual target is no longer needed.
Select the correct box model.
Avoid changing observed dimensions without checking existing values.
Keep callback operations efficient.
Avoid unnecessary React state updates.
Use CSS container queries for styling-only requirements.
Test components with different parent sizes.
Provide a fallback for unsupported environments.
Use browser developer tools to investigate unexpected layout behaviour.
Build a dashboard with multiple cards that change their layout according to the dimensions of their containers.
Use Resize Observer to monitor individual cards and adjust their internal components.
Create a chart that automatically updates its dimensions when the user resizes the surrounding panel.
Integrate a charting library or use canvas for custom rendering.
Develop a text component that changes its presentation according to the available container width.
Use carefully controlled size thresholds to avoid repeated layout changes.
Build an interface with a draggable sidebar.
Observe the main content area and update its layout when the sidebar changes width.
Create a basic code editor interface with resizable panels for the editor, file explorer and output console.
Use Resize Observer to detect changes and adapt each panel's internal layout.
Developers should understand:
HTML and CSS fundamentals.
JavaScript and DOM manipulation.
Browser APIs.
CSS box model.
Responsive web design.
JavaScript callbacks.
Asynchronous browser behaviour.
React hooks, where applicable.
Performance optimisation.
DOM lifecycle and memory management.
A strong understanding of the CSS box model is particularly useful because Resize Observer provides different types of dimension measurements.
Resize Observer is a specialised browser API that can strengthen frontend development skills.
Its practical applications are relevant to developers working on:
Frontend Development.
JavaScript Development.
React Development.
Dashboard Development.
Data Visualisation.
Web Application Development.
UI Engineering.
Interactive Web Interfaces.
Understanding this API can help developers build components that work reliably in complex layouts, especially when users can resize panels or when application content changes dynamically.
It is not a standalone professional qualification, but it is a useful addition to modern frontend development knowledge.
A practical learning sequence can help developers understand the API:
Learn the CSS box model: Understand content, padding, borders and element dimensions.
Practise DOM selection: Learn how JavaScript accesses and modifies HTML elements.
Create your first observer: Use the ResizeObserver constructor and callback.
Explore observation methods: Practise observe(), unobserve() and disconnect().
Study box measurements: Compare content-box, border-box and device-pixel-content-box.
Build a responsive component: Create a panel that responds to element-level size changes.
Integrate React: Develop a reusable custom hook for observing element dimensions.
Study performance: Learn how to avoid repeated layout changes and unnecessary rendering.
Developers interested in strengthening their frontend knowledge can explore EasyShiksha Online Courses, search relevant learning resources through the EasyShiksha course directory, or explore the Web Development Course.
The Resize Observer API makes it possible to monitor individual element dimensions and respond to layout changes through JavaScript.
It is especially valuable for dashboards, data visualisations, resizable panels, embedded widgets and dynamic frontend components.
By understanding ResizeObserver, ResizeObserverEntry, observation methods and box models, developers can build interfaces that respond to component dimensions rather than depending entirely on browser window resizing.
When combined with React, CSS container queries and appropriate performance practices, Resize Observer becomes a useful tool for creating flexible and maintainable web applications.
The Resize Observer API is a browser feature that allows JavaScript to monitor changes in the dimensions of HTML and SVG elements.
ResizeObserver is the main interface of the API. Developers create an instance and provide a callback that receives notifications when observed elements change size.
The window resize event detects changes to the browser window, whereas Resize Observer monitors individual elements. An element can change size even when the browser window remains unchanged.
The observe() method starts monitoring the dimensions of a specified element. It can also accept options to select the box model being observed.
The unobserve() method stops monitoring a particular element while allowing the observer to continue monitoring other registered elements.
The disconnect() method stops monitoring all elements associated with a ResizeObserver instance.
ResizeObserverEntry is an object passed to the observer callback. It contains information about the observed element and its updated dimensions.
contentBoxSize provides information about the element's content area, while borderBoxSize provides information about its complete border box, including padding and borders.
It reports the content dimensions in device pixels before CSS transforms are applied to the element or its ancestors. It is useful for applications that need precise graphics rendering.
Yes. One ResizeObserver instance can observe multiple elements by calling observe() for each target.
Yes. React developers can use it with useEffect, useRef and useState to create responsive components and reusable custom hooks.
No. Media queries respond to viewport or other media conditions, while Resize Observer detects element-level size changes. Both can be used together.
CSS container queries change styling according to container conditions. Resize Observer provides JavaScript notifications about element size changes, making it useful when application logic needs updated dimensions.
A loop can occur when an observer callback changes the dimensions of an observed element, triggering further resize notifications. Developers should avoid uncontrolled changes to observed dimensions.
Yes. It can monitor chart containers and notify the application when their dimensions change, allowing chart rendering logic to adapt.
Yes. The API can observe supported SVG elements and report changes to their bounding box dimensions.
Yes. When content changes affect an observed element's dimensions, Resize Observer can report the resulting size change.
Yes. It is supported across modern major browsers and has been widely available since 2020. Developers should still check compatibility for their target environments.
They should keep callbacks efficient, avoid unnecessary dimension changes, limit observations to relevant elements and disconnect observers when they are no longer needed.
Developers should use it when JavaScript needs to respond to changes in individual element dimensions, particularly in dashboards, resizable layouts, charts, editors and dynamic components.
More News Click here
Discover thousands of colleges and courses, enhance skills with online courses and internships, explore career alternatives, and stay updated with the latest educational news..
Gain high-quality, filtered student leads, prominent homepage ads, top search ranking, and a separate website. Let us actively enhance your brand awareness.