'Chart.js in flex element overflows instead of shrinking

I have tried setting the min-width to 0 on the wrapper div for chart.js, but the chart will grow and then not shrink back down if you drag the window around.

I can't figure it out! The only thing I can do is set width to 99% but then the chart is no longer aligned with my other divs. I've been working on this for days, please help!

Q: How can I get chart.js to be 100% width, and grow/shrink to it's bounding size.

to reproduce, go to the example and if you close the menu, the chart grows, and if you open it, the chart does not shrink back down. it maintains it's size and overflows to the right.

note: my actual project has two separate components for the chart and side bar. So a calc solution doesn't work in this case, I don't want to tightly couple any components to maintain good practice.

Here is my StackBlitz working example

here are pictures to show the reproduction:

  1. chart is the right size, menu open enter image description here

  2. chart grows when you close the menu (the size is still correct) enter image description here

  3. open the menu, and the chart overflows right enter image description here



Solution 1:[1]

Update: This solution stopped working with chart.js 3

I had similar problems with a markup like this:

<div style="display: flex; flex-direction: column">
  <h2>...</h2>
  <div class="chart-container" style="position: relative; flex: 1">
    <canvas></canvas>
  </div>
  <span>...</span>
  <span>...</span>
</div>

My outermost div was in a css-grid, maybe that also played a role.

Anyhow, I diagnosed the problem to be this: Even though I applied { responsive: true, maintainAspectRatio: false } to the options of chart.js, the chart had a fixed size, which caused the chart-container not to shrink (even when overflow: hidden was applied, I don't fully understand why). This caused the div element chartjs inserts to detect size changes to never change its height.

So the solution was to simply override the height on the canvas to 100%: canvas {height: 100%!important}.

This allows the canvas container to shrink, causing the size-detection div to shrink, causing a re-render of the canvas, which prevents aspect-ratio issues.

Solution 2:[2]

Here your canvas is having width inside absolute parents so its recommended to change the values dynamically using JavaScript (angular in your case). But since you are looking for CSS based solution here is what you can add in your app.components.css file:

.sidebar-wrapper.shrink + div.main-wrapper canvas {
  width: calc(100vw - 40px) !important;
}
.sidebar-wrapper:not(.shrink) + div.main-wrapper canvas {
  width: calc(100vw - 230px) !important;
}

Here is the working example : https://chartjs-overflow-ex-vlsqmn.stackblitz.io/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 tam