[Chartjs]-Chart.js in flex element overflows instead of shrinking

33πŸ‘

βœ…

(Copied from my comment.)

I can’t get StackBlitz to run (JS errors due to tracking protection in Firefox) so I can’t verify this, but I had that exact issue in my flex layout and solved it by ensuring overflow: hidden was set on the parent (and ancestor) flex elements. A cursory look at your CSS shows this is only done on .page-wrapper.

3πŸ‘

Wrapping the canvas in a div with width 100% and and setting the canvas to max-width 100% works for me:

<div style="width: 100%; position: relative;">
    <canvas id="chart" style="max-width: 100%;"></canvas>
</div>

2πŸ‘

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.

0πŸ‘

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/

0πŸ‘

Wrapping the canvas in a div with max-width 70% works for me:

<div class="division-chart-wrap">
    <canvas id="chart" ></canvas>
</div>
<style>
      .division-chart-wrap {
        flex: 1 1 18rem;
        min-height: 12rem;
        position: relative;
        max-width: 70%;
      }
</style>

Leave a comment