DEV Community

Cover image for Creating a stacked bar chart using only CSS

Creating a stacked bar chart using only CSS

Kevin Pennekamp on January 23, 2023

In various projects, I always seem to struggle with responsive charts. These libraries generate charts in SVGs, often with fixed dimensions or rati...
Collapse
 
suman373_30 profile image
Suman Roy

Quite helpful for those who don't want to integrate dependency !

Collapse
 
udanielnogueira profile image
Daniel Nogueira

Good tutorial, thanks!

Collapse
 
rickdelpo1 profile image
Rick Delpo

I finally got around to reformatting and populating this bar chart.

This post uses moment.js for grouping by months
dev.to/rickdelpo1/stacked-bar-char...

This post ditches moment.js and I use array.reduce to group my months
dev.to/rickdelpo1/how-to-populate-...

Collapse
 
rickdelpo1 profile image
Rick Delpo

Nice Post! I like the idea of not using a JS chart library. Can we add a Javascript Fetch to populate the stacked bars from a JSON datasource?

Collapse
 
vyckes profile image
Kevin Pennekamp

That is definitely possible. You can wrap this code in a React/Vue/Svelte component for instance and populate everything.

Collapse
 
rickdelpo1 profile image
Rick Delpo

thanks, I was thinking of a plain javascript version. Maybe some of your viewers have some sample code? I am new to bar charts.

Thread Thread
 
leandro_n_ortiz profile image
Leandro Ortiz • Edited

I don't have a sample code, but with plain javascript, you can use fetch to perform API calls and get the values you need.
Then, you just need to pass it to the "style" property to work with the example of this post.
For "fetch" documentation:
developer.mozilla.org/en-US/docs/W...

It's not usual to develop an application with API calls without any framework or rendering lib, but it would be something like this:

fetch('https://jsonplaceholder.typicode.com/todos/')
 .then(response => response.json())
 .then(list => {
    list.forEach(item => {
      document.getElementById(`todo-${item.id}`).style = `--bar-ratio: ${item.id}%;`
    });
  });
Enter fullscreen mode Exit fullscreen mode

I couldn't find a mock server that return a useful number to populate the chart, so I used the "id" of the todo list as the value...sorry

Then the HTML would be:

<div class="chart">
    <div id="todo-1" class="bar" style=""></div>
    <div id="todo-2" class="bar" style=""></div>
    <div id="todo-3" class="bar" style=""></div>
    <div id="todo-4" class="bar" style=""></div>
    <div id="todo-5" class="bar" style=""></div>
</div>
Enter fullscreen mode Exit fullscreen mode

P.S.: It would be much easier in React heheh

Thread Thread
 
rickdelpo1 profile image
Rick Delpo

Hey thanks very much for the response. When I get a chance I will update my code and post here. It is not a high priority right now but I have a use case that I want to implement over the next few months. I really want to stay with Plain JS vs React