Chartjs-Center chart.js canvas in a container without added buffer

1👍

I ended up using some Javascript:

const chartContainers = Array.from(document.getElementsByClassName('chart-container'));
const chartMaxWidthPercent = 0.9;
const chartMaxHeightPercent = 0.7;

function resizeChartContainers() {
  let maxWidth = chartMaxHeightPercent * window.innerWidth;
  let maxHeight = chartMaxHeightPercent * window.innerHeight;
  let width = Math.min(maxWidth, maxHeight * 2);
  let height = Math.min(maxHeight, maxWidth / 2);
  chartContainers.forEach(container => {
    container.style.width=`${width}px`;
    container.style.height=`${height}px`;
  });
}

window.addEventListener("resize", resizeChartContainers);
resizeChartContainers(); // Initial resize

Then in my CSS I removed the height and width specifications:

.chart-container {
  position: relative;
  margin: 0 auto;
}

Leave a comment