Very Simple Responsive Bar Chart With CSS JS (Free Download)

Welcome to a tutorial on how to create a simple responsive bar chart with pure CSS and Javascript. So you may be looking for ways to create bar charts, but do not want to load any of those bloated complicated libraries. So here it is, a simple lightweight bar chart – Read on!

ⓘ I have included a zip file with all the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

 

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK START & DEMO

bar-chart.html
<!-- (A) LOAD CSS + JS -->
<script src="bar-chart.js"></script>
<link rel="stylesheet" href="bar-chart.css">
 
<!-- (B) DIV TO GENERATE BAR CHART -->
<div id="demoA"></div>
<div id="demoB"></div>
 
<!-- (C) CREATE CHARTS -->
<script>
// (C1) HORIZONTAL BAR CHART
bchart.draw({
  type : "h",
  target : document.getElementById("demoA"),
  data: [["First", 33], ["Second", 100], ["Third", 70]]
});
 
// (C2) VERTICAL BAR CHART
bchart.draw({
  type : "v",
  target : document.getElementById("demoB"),
  data: [
    ["First", 33, "#4e0707"],
    ["Second", 100, "#077419"],
    ["Third", 70, "#124789"]
  ]
});
</script>

For you guys who just want to use this as a “plugin” without reading the rest of the tutorial:

  1. Load the Javascript and CSS. Captain Obvious at your service.
  2. Define a <div> to create the bar chart.
  3. Call bchart.draw() to generate the bar chart.
    • type The “orientation” of the chart. h for horizontal and v for vertical.
    • target Target <div> to generate the chart in.
    • data Array of data to draw, in the format of [LABEL, QUANTITY, OPTIONAL COLOR].

 

 

RESPONSIVE BAR CHART

All right, let us now get a little bit more into the details of the bar chart – This is for you guys who may want to “deep customize”.

 

PART 1) THE JAVASCRIPT

bar-chart.js
var bchart = {
  // (A) HELPER FUNCTION - GENERATE RANDOM DARK COLOR
  // source: https://gist.github.com/Chak10/dc24c61c9bf2f651cb6d290eeef864c1
  rcolor : () => {
    let lum = -0.25, rgb = "#", c, i,
        hex = String("#" + Math.random().toString(16).slice(2, 8).toUpperCase()).replace(/[^0-9a-f]/gi, "");
    if (hex.length < 6) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; }
    for (i = 0; i < 3; i++) {
      c = parseInt(hex.substr(i * 2, 2), 16);
      c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
      rgb += ("00" + c).substr(c.length);
    }
    return rgb;
  },
 
  // (B) DRAW BAR CHART
  draw : instance => {
    // (B1) INIT CHART CONTAINER
    let hor = instance.type=="h";
    instance.target.classList.add((hor ? "hbar" : "vbar"));
    instance.target.innerHTML = "";
 
    // (B2) GET LARGEST VALUE FROM DATA
    let largest = 0;
    instance.data.forEach(el => {
      if (el[1] > largest) { largest = el[1]; }
    });
 
    // (B3) DRAW CHART
    let bars = new DocumentFragment(), bar, percent;
    instance.data.forEach(el => {
      // (B3-1) CREATE <DIV> BAR
      bar = document.createElement("div");
      bars.appendChild(bar);
 
      // (B3-2) SET WIDTH/HEIGHT
      percent = Math.ceil((el[1] / largest) * 100) + "%";
      if (hor) { bar.style.width = percent; } else { bar.style.height = percent; }
 
      // (B3-3) BACKGROUND COLOR & TEXT
      bar.style.background = el[2] ? el[2] : bchart.rcolor();
      bar.innerHTML = el[0] + ": " + el[1];
    });
    instance.target.appendChild(bars);
  }
};

That’s all for the Javascript, there are only 2 functions here.

  1. rcolor() A helper function to generate a random dark color.
  2. draw() You already know this one, used to generate the bar chart itself. Not going to explain step-by-step, we are essentially just inserting <div> bars into the specified container, and setting the width/height.

 

 

PART 2) GENERATED HTML

<!-- (A) HORIZONTAL -->
<div id="demoA" class="hbar">
  <div style="width: 33%; background: rgb(155, 48, 77);">First: 33</div>
  <div style="width: 100%; background: rgb(104, 137, 11);">Second: 100</div>
  <div style="width: 70%; background: rgb(128, 6, 26);">Third: 70</div>
</div>
 
<!-- (B) VERTICAL -->
<div id="demoB" class="vbar">
  <div style="height: 33%; background: rgb(78, 7, 7);">First: 33</div>
  <div style="height: 100%; background: rgb(7, 116, 25);">Second: 100</div>
  <div style="height: 70%; background: rgb(18, 71, 137);">Third: 70</div>
</div>

Yep, this is what the “complicated Javascript” above actually does. Insert <div> bars into the container, and calculate the width/height accordingly.

 

 

PART 3) THE CSS

bar-chart.css
/* (A) SHARED FONT & SIZING */
.hbar, .vbar, .hbar *, .vbar * {
  font-family: Arial, Helvetica, sans-serif;
  box-sizing: border-box;
}
 
/* (B) BAR CHART CONTAINER */
/* (B1) SHARED */
.hbar, .vbar {
  display: flex;
  width: 100%;
  border: 1px solid #333;
  margin: 20px 0;
}
 
/* (B2) HORIZONTAL */
.hbar {
  flex-direction: column;
  background: repeating-linear-gradient(
    to right, #f2f2f2, #ddd 2px, #fff 2px, #fff 5%
  );
}
 
/* (B3) VERTICAL */
.vbar {
  align-items: flex-end;
  height: 400px;
  background: repeating-linear-gradient(
    to bottom, #f2f2f2, #ddd 2px, #fff 2px, #fff 10%
  );
}
 
/* (C) EACH INDIVIDUAL BAR */
/* (C1) SHARED */
.hbar div, .vbar div {
  color: #fff;
  padding: 10px;
}
 
/* (C2) HORIZONTAL */
.hbar div { margin: 5px 0; }
 
/* (C3) VERTICAL */
.vbar div { width: 100%; }

We are just using CSS flexbox to build the bar charts here, the rest are pretty much cosmetics.

 

 

EXTRA BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has given you some good ideas on how to create your bar charts, and if you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *