CodeBlanks Logo Icon CodeBlanks

ResizeObserver in depth

JavaScript course · Expert · Lesson 14/63

Learn element size changes and content box size with ResizeObserver.

ResizeObserver and contentBoxSize

ResizeObserver watches an element's size changes. The callback receives an entries array; each entry carries the new size of one watched element. The basic field entry.contentRect gives width and height.

For finer detail use entry.contentBoxSize. It is an array; each item has inlineSize (horizontal) and blockSize (vertical). Following the CSS Box Model it measures the content box only, without padding or border.

The borderBoxSize difference

borderBoxSize measures the whole box, including padding and border. So contentBoxSize gives the content area only, while borderBoxSize gives the full visible area. This matters in layout math that depends on the CSS box-sizing setting.

Some browsers also expose devicePixelContentBoxSize, which gives sizes in physical pixels for high DPI screens. Pick the one that fits your need.

Exercise Watch the box element's width

Create a ResizeObserver. The callback takes entries; for each entry log entry.contentBoxSize[0].inlineSize to the console. Watch the box element.

Show example solution
1. Create with new ResizeObserver((entries) => {...}).
2. Loop through entries and log entry.contentBoxSize[0].inlineSize.
3. Start with observer.observe(box).

Example solution:
const observer = new ResizeObserver((entries) => {
  for (const entry of entries) {
    console.log(entry.contentBoxSize[0].inlineSize);
  }
});
observer.observe(box);

Test yourself

  1. observe call

    observer.____(box);
    Show answer
    observer.observe(box);
  2. What is the difference between contentBoxSize and borderBoxSize in ResizeObserver?

    • contentBoxSize includes padding, borderBoxSize does not
    • They are exactly the same
    • contentBoxSize measures the content, borderBoxSize measures the whole box including padding and border
    • borderBoxSize gives only the width
    Show answer

    contentBoxSize measures the content, borderBoxSize measures the whole box including padding and border — Correct. contentBoxSize measures the content area, borderBoxSize measures the whole box including padding and border.

  3. Match ResizeObserverSize fields

    inlineSize
    Horizontal content size
    blockSize
    Vertical content size
    contentBoxSize
    Content box
    borderBoxSize
    Border box

All lessons in Expert