how to create a bar chart using html, css and javascript

11/09/2020    By: christoper unum

Bar charts can come in handy especially when you are trying to represent information on your website graphically. In this tutorial, we will be creating a bar chart that displays the names of students and their overall exam scores using HTML, CSS, and JavaScript as shown above. 


Basic knowledge of HTML, CSS and JavaScript is required to fully grasp the concepts in this tutorial.


To begin, we have to create the container we will rendering the bars to using HTML as shown below

<div id="chart-out">
  <div id="chart-in">


Now we apply styles to the HTML code

body {
  font-family"Fira Sans"sans-serif;
  padding:15px 0;
  margin0 auto;
  margin:0 auto;
  border-left:1px solid green;
  border-bottom:1px solid green;
  margin:5px 0;


Below is the JavaScript code that takes the arrays of the students and their grades and converts it into bars

//student names
const students = ["James""Ruth""John""Rose""Jerry""Chris""Mathew","Mark","Mary""Linda"];
//grades of students
const marks = [78538983939932657341];
//grades of students for sorting
const marks2 = [78538983939932657341];

//gets the highest mark
const highestMark = (marksArray) => {
  //return marksArray.sort()[marksArray.length-1];
  let marksArray2 = marksArray;
  marksArray2.sort((a, b) => {return a-b});
  return marksArray[marksArray.length-1];

//stores the highest mark in a variable
let highest = highestMark(marks2);

//gets the percentage of the marks with respect to the highest mark
const getBarPercentage = (mark, highest) => {
  return (mark*100)/highest;

//adds bars to the div element
const addBar = (name, value, percent) => {
  let infoButton = document.createElement('button');
  let infoText = document.createTextNode(`${name} : ${value}`);
  let barIn = document.createElement("div");
  barIn.classList.add("bar-in"); = `${percent}%`;
  let barOut = document.createElement("div");

//displays all the bars
const displayBars = (students,marks,highest) => {
  for(let i=0; i<students.length; i++){
    addBar(students[i], marks[i], getBarPercentage(marks[i], highest));
displayBars(students, marks, highest);


Thats our bar chat, you can add you tweaks and make your own version of it.

Recent Posts

blog image
blog image
blog image

Our Newsletters