DEV Community

Jeevan Kumar Karre
Jeevan Kumar Karre

Posted on

Create beautiful Bar Chart using Chart.js and Tailwind CSS

<div class="container mx-auto px-4">
  <div class="card bg-white rounded-lg shadow-lg">
    <div class="card-header bg-gray-100 py-4 px-6">
      <h2 class="text-xl font-bold">Bar Chart</h2>
    </div>
    <div class="card-body">
      <canvas id="barChart"></canvas>
    </div>
  </div>
</div>

Enter fullscreen mode Exit fullscreen mode

JavaScript (using Chart.js):

import Chart from 'chart.js';
const data = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June'],
  datasets: [
    {
      label: 'Sales',
      data: [120, 200, 150, 300, 250, 180],
      backgroundColor: [
        'rgba(129, 212, 250, 0.8)',
        'rgba(129, 212, 250, 0.8)',
        'rgba(129, 212, 250, 0.8)',
        'rgba(129, 212, 250, 0.8)',
        'rgba(129, 212, 250, 0.8)',
        'rgba(129, 212, 250, 0.8)',
      ],
      borderColor: [
        'rgba(59, 130, 246, 1)',
        'rgba(59, 130, 246, 1)',
        'rgba(59, 130, 246, 1)',
        'rgba(59, 130, 246, 1)',
        'rgba(59, 130, 246, 1)',
        'rgba(59, 130, 246, 1)',
      ],
      borderWidth: 1,
    },
  ],
};

const options = {
  scales: {
    x: {
      display: false,
    },
    y: {
      display: false,
    },
  },
};

const ctx = document.getElementById('barChart').getContext('2d');
new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options,
});

Enter fullscreen mode Exit fullscreen mode

CSS (using Tailwind CSS):

.container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card {
  width: 400px;
}

.card-header {
  border-bottom-width: 1px;
  border-color: rgba(0, 0, 0, 0.1);
}

.card-body {
  height: 300px;
}

canvas {
  width: 100% !important;
  height: 100% !important;
}

Enter fullscreen mode Exit fullscreen mode

In the above example, we create a bar chart using Chart.js and customize the appearance using Tailwind CSS classes.

The chart is displayed within a card component, and the x-axis and y-axis labels are removed by setting display: false in the chart options.

The card component has a rounded border (rounded-lg) and a shadow (shadow-lg) applied.

The bar chart uses a gradient background (bg-gradient) defined in the dataset's backgroundColor property.

Include this chart.js cdn inside head.

Top comments (0)