< BACK TO COMPONENTS

Creating a Responsive Chart with HTML, CSS, and Chart.js (Source Code)

Faraz

By Faraz -

Unlock the power of data visualization with our step-by-step Chart.js tutorial. From setup to customization, become a pro in creating dynamic charts effortlessly.


Creating a Responsive Chart with HTML, CSS, and Chart.js.jpg

Welcome to the world of Chart.js, a powerful JavaScript library for creating beautiful and interactive charts on the web. Whether you're a beginner or an experienced developer, this tutorial will guide you through the process of harnessing the potential of Chart.js.


Let's start creating visually stunning and responsive charts using HTML, CSS, and JavaScript library Chart.js step by step.


Join My Telegram Channel to Download the Project Source Code: Click Here


Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

Before diving into Chart.js, let's set up our development environment to ensure a smooth experience.


Steps:


  1. Download and include Chart.js in your project.
  2. Create an HTML file and link the Chart.js script.
  3. Set up a canvas element for rendering the chart.

Let's break down each part of the HTML code


1. <!DOCTYPE html>: This declaration defines the document type and version of HTML being used. In this case, it specifies that the document is an HTML5 document.


2. <html lang="en">: This opening tag marks the beginning of the HTML document. The lang attribute is set to "en" for English, indicating the language of the document.


3. <head>: This section contains meta-information about the HTML document, such as character set, viewport settings, title, external stylesheets, and scripts.


  • <meta charset="UTF-8">: Specifies the character encoding for the document as UTF-8, which supports a wide range of characters.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport settings, ensuring that the webpage scales appropriately on different devices.
  • <title>Charts using JavaScript</title>: Sets the title of the HTML document that will be displayed on the browser tab.
  • <link rel="stylesheet" href="style.css">: Links an external CSS (Cascading Style Sheets) file named "style.css" to the HTML document. This file contains styles for the webpage.
  • <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>: Imports the Chart.js library from a content delivery network (CDN). This library is used for creating charts and graphs with JavaScript.

4. <body>: This section contains the content of the HTML document that will be displayed on the webpage.


  • <div class="widget">: Defines a container with the class "widget." This container is used to hold the chart.
  • <canvas id="revenues"></canvas>: Creates a HTML5 canvas element with the id "revenues." The Chart.js library will use this canvas to render the chart.
  • <script src="script.js"></script>: Links an external JavaScript file named "script.js" to the HTML document. This file contains the JavaScript code that uses Chart.js to generate and render the chart.

Step 2 (CSS Code):

Define a responsive container for your chart and style it using CSS. This step ensures your chart looks visually appealing and adapts to different screen sizes. Let's break down each part of the CSS code


1. :root: This pseudo-class represents the highest-level parent in the document tree, usually the <html> element. Custom properties or variables are defined inside :root. In this case, three custom properties are defined:


  • --background: Sets the background color to a dark grayish color (#1A1C1E).
  • --background-widget: Sets the background color for a widget to a slightly lighter shade of gray (#1E2023).
  • --primary: Sets a primary color to a light golden shade (#F6C356).

2. *: This is a universal selector that targets all elements on the page. The following styles are applied to all elements:


  • margin: 0;: Removes any default margin.
  • padding: 0;: Removes any default padding.
  • box-sizing: border-box;: Ensures that the total width and height of an element includes padding and border, but not margin.

3. body: Styles applied to the <body> element:


  • display: flex;: The body is set to a flex container.
  • justify-content: center;: Centers content along the horizontal axis.
  • align-items: center;: Centers content along the vertical axis.
  • flex-direction: column;: Arranges children in a column layout.
  • font-family: 'Open Sans', sans-serif;: Sets the font family for the entire document to 'Open Sans' or a sans-serif fallback.
  • background-color: var(--background);: Sets the background color to the previously defined --background variable.
  • height: 100vh;: Sets the height of the body to 100% of the viewport height.

4. .widget: Styles applied to elements with the class "widget":


  • border-radius: 32px;: Applies a rounded border with a radius of 32 pixels.
  • background-color: var(--background-widget);: Sets the background color to the previously defined --background-widget variable.
  • padding: 16px;: Adds 16 pixels of padding inside the widget.
  • max-width: 600px;: Sets the maximum width of the widget to 600 pixels.
  • width: 100%;: Makes the widget take up 100% of the available width.
  • min-width: 300px;: Sets the minimum width of the widget to 300 pixels.

5. .widget canvas: Styles applied to the canvas element inside elements with the class "widget":


  • min-height: 280px;: Sets the minimum height of the canvas to 280 pixels.
:root {
    --background: #1A1C1E;
    --background-widget: #1E2023;
    --primary: #F6C356;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    font-family: 'Open Sans', sans-serif;
    background-color: var(--background);
    height: 100vh;
}

.widget {
    border-radius: 32px;
    background-color: var(--background-widget);
    padding: 16px;
    max-width: 600px;
    width: 100%;
    min-width: 300px;
}

.widget canvas {
    min-height: 280px;
} 

Step 3 (JavaScript Code):

Initialize the chart in your JavaScript file, customizing options and appearance. This step brings your chart to life and makes it interactive for users.


This JavaScript code creates a bar chart using the Chart.js library to visualize revenue data for each month of the year 2023. Let's break down the code:


1. Canvas Element Selection:


const ctx = document.getElementById("revenues");

  • It selects the HTML canvas element with the id "revenues" where the chart will be rendered.

2. Chart Configuration:


Chart.defaults.color = "#FFF";
Chart.defaults.font.family = "Open Sans";

  • It sets default styles for the chart. The chart will have white text (#FFF) and will use the "Open Sans" font family.

3. Chart Initialization:


new Chart(ctx, {
  type: "bar",
  data: {
    // Data configuration goes here...
  },
  options: {
    // Chart options go here...
  },
});

  • It initializes a new bar chart on the selected canvas (ctx). The chart type is set to "bar."

4. Data Configuration:


labels: ["Jan", "Feb", ..., "Dec"],
datasets: [
  {
    label: "Revenue (million [$])",
    data: [5.2, 7.8, ..., 60],
    backgroundColor: "#F4BD50",
    borderRadius: 6,
    borderSkipped: false,
  },
],

  • It specifies the chart data, including labels for each month and a dataset for revenue values. The dataset has styling properties like background color (#F4BD50), border radius, and whether borders should be skipped.

5. Chart Options:


options: {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { display: false },
    title: {
      display: true,
      text: "Your Company Revenue In 2023",
      // Title styling goes here...
    },
    tooltip: {
      backgroundColor: "#27292D",
    },
  },
  scales: {
    x: {
      // X-axis styling goes here...
    },
    y: {
      // Y-axis styling goes here...
    },
  },
},

It sets various options for the chart, such as responsiveness, title display, legend display, tooltip styling, and axis configurations.


  • The title is set to "Your Company Revenue In 2023."
  • Tooltip background color is set to #27292D.
  • X and Y axes are configured with styles for grid lines, borders, and titles.
const ctx = document.getElementById("revenues");

Chart.defaults.color = "#FFF";
Chart.defaults.font.family = "Open Sans";

new Chart(ctx, {
  type: "bar",
  data: {
    labels: [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
    ],
    datasets: [
      {
        label: "Revenue (million [$])",
        data: [
          5.2, 7.8, 12.3, 11.2, 11.5, 28.8, 35.5, 40, 42.5, 45.5, 50.5, 60,
        ],
        backgroundColor: "#F4BD50",
        borderRadius: 6,
        borderSkipped: false,
      },
    ],
  },
  // continuation

  options: {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
      },
      title: {
        display: true,
        text: "Your Company Revenue In 2023",
        padding: {
          bottom: 16,
        },
        font: {
          size: 16,
          weight: "normal",
        },
      },
      tooltip: {
        backgroundColor: "#27292D",
      },
    },
    scales: {
      x: {
        border: {
          dash: [2, 4],
        },
        grid: {
          color: "#27292D",
        },
        title: {
          text: "2023",
        },
      },
      y: {
        grid: {
          color: "#27292D",
        },
        border: {
          dash: [2, 4],
        },
        beginAtZero: true,
        title: {
          display: true,
          text: "Revenue (million [$])",
        },
      },
    },
  },
});

Final Output:

Creating a Responsive Chart with HTML, CSS, and Chart.js.gif

Conclusion:

In conclusion, you've embarked on a journey to master the creation of captivating charts using Chart.js. From setting up your environment to customizing appearance, adding labels, and delving into real-time data visualization, you've gained a comprehensive understanding of this powerful JavaScript library.


As you apply these newfound skills, remember to explore further possibilities through Chart.js documentation for advanced features. Troubleshooting common issues and adhering to best practices will ensure your charts not only look impressive but also function seamlessly.


Now equipped with the ability to seamlessly integrate dynamic and visually stunning charts into your web projects, you're ready to elevate your data visualization game. Happy coding, and may your charts be both informative and visually striking!


Code by: Atheros

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Related Post