Search code examples
javascriptcsscss-gridresize-observer

ResizeObserver not working properly for setting css-grid item width


I have a CSS-Grid wrapper with items in. Each item has a ResizeObserver, listening for size changes in order to resize a chart that is rendered inside the item.

On resize, the chart width will be set to the items width. The problem is, that the ResizeObserver won't fire any events when the item is resized to a smaller width.

Here is a simple reproduction:

<div class="wrapper">
  <div class="item" id="item-1">
    <div id="item-1-child">Content</div>
  </div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
.wrapper {
  display: grid;
  gap: 10px;
}

.item {
  background: orange;
  width: 100%;
  height: 20px;
}
const el = document.getElementById('item-1');
const elChild = document.getElementById('item-1-child')

const observer = new ResizeObserver(entries => {
  console.log('resize', el.offsetWidth)
  elChild.style.width = `${el.offsetWidth}px`;
});

observer.observe(el);

When I change the display: grid; on the .wrapper to display: block;, it works as intended. So something related to CSS-Grid is causing some trouble here.


Solution

  • Try adding the grid-template-columns property to the grid container ("wrapper"), which defines the track sizing for the grid columns. This will allow you to limit the width of the "item-1-child".

    .wrapper {
      display: grid;
      gap: 10px;
      grid-template-columns: 100%;
    }
    
    .item {
      background: orange;
      width: 100%;
      height: 20px;
    }
    

    The reason for this problem is that grid-template-columns is defaulted to none:

    Indicates that there is no explicit grid. Any columns will be implicitly generated and their size will be determined by the grid-auto-columns property.

    -- https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns#values

    Then grid-auto-columns is defaulted to auto:

    Is a keyword that is identical to maximal content if it's a maximum. As a minimum it represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track.

    -- https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-columns#values