Simple Horizontal Segmented Bar Chart With CSS

13th March 2021 - 9 minutes read time

Bar charts are powerful ways to show the relationships between different data items. If the data you want to show is discrete then a simple horizontal segmented bar chart is a good idea. You can easily change a collection of numbers into a related set of attributes.

To display this bar chart you don't need a large JavaScript library or an backend charting system, you just need a few lines of markup and some styles. Here is all of the markup needed to generate the bar chart. This consists of a wrapper element and four inner elements that make up the data of the bar chart. Note that the width of each element is pre-calculated to be 25%. I'll address the maths involved in this later in the post.

  1. <div class="chart">
  2. <div style="width:25%" class="red start"></div>
  3. <div style="width:25%" class="blue"></div>
  4. <div style="width:25%" class="green"></div>
  5. <div style="width:25%" class="cyan end"></div>
  6. </div>

The aren't a lot of styles involved in this bar chart, in fact, most of the styles are involved with setting the colours of the elements of the chart. What we need to do is set up the width of the wrapper and then float the elements to the left. The width of each element being under a total of 100% means that the chart fits nicely into a single line. The .start and .end classes make the ends of the chart nicely rounded ends.

  1. .chart {
  2. height: 2rem;
  3. width: 30rem;
  4. }
  5.  
  6. .chart div {
  7. height: 100%;
  8. float: left;
  9. }
  10.  
  11. .chart .start {
  12. border-radius: 2rem 0 0 2rem;
  13. }
  14.  
  15. .chart .end {
  16. border-radius: 0 2rem 2rem 0;
  17. }
  18.  
  19. .chart .red {
  20. background-color: red;
  21. }
  22.  
  23. .chart .blue {
  24. background-color: blue;
  25. }
  26.  
  27. .chart .green {
  28. background-color: green;
  29. }
  30.  
  31. .chart .cyan {
  32. background-color: cyan;
  33. }

Putting these together produces the following bar chart.

Horizontal segmented bar chart

Working Out The Widths

How do we figure out the widths of the elements? This requires a bit of maths to map the elements against a range of the outer wrapper (ie, 100%). Do to this we add all of the elements together and figure out the map of each item against the range of 0 to 100. In the example above we are mapping four equal values to the bar chart, so if we assume that the data is four values of 100 each then the maths works out as follows.

  1. 100 + 100 + 100 + 100 = 400
  2. 0 + (400 - 0) * ((100 - 0) / (0 - 100))
  3. The mapped value is: 25

I have previously written about creating a mapping function in PHP, and I have also created a tool on this site that allows you to use the mapping function itself. Here is a JavaScript version of the map function previously written in PHP.

  1. function map(value, valueRangeStart, valueRangeEnd, newRangeStart, newRangeEnd) {
  2. return newRangeStart + (newRangeEnd - newRangeStart) * ((value - valueRangeStart) / (valueRangeEnd - valueRangeStart));
  3. }

This this function we can start looking at dynamically resizing the chart.

Dynamically Sizing The Chart

Whilst adding the widths into the page creates a perfectly usable chart, it does mean we need to work out the sizes before rendering the page. We can solve this by adding in an extra class to each of the chart items. If we add an incrementing class value to each of the chart items we can address each item in the chart using a simple loop. Here is the new markup.

  1. <div class="chart">
  2. <div style="width:25%" class="item1 red start"></div>
  3. <div style="width:25%" class="item2 blue"></div>
  4. <div style="width:25%" class="item3 green"></div>
  5. <div style="width:25%" class="item4 cyan end"></div>
  6. </div>

Using the width function we can start to make the chart widths a little bit easier to work out. If we keep the widths of the elements at 25% each then we can use some JavaScript code within the page to automatically resize the elements to the desired widths as the page is loaded. The following JavaScript code takes four values of 300, 80, 270, 90 and work out their relative widths. These widths are then applied directly to the chart items using their new incrementing class names.

  1. function map(value, valueRangeStart, valueRangeEnd, newRangeStart, newRangeEnd) {
  2. return newRangeStart + (newRangeEnd - newRangeStart) * ((value - valueRangeStart) / (valueRangeEnd - valueRangeStart));
  3. }
  4.  
  5. var chart = document.getElementsByClassName('chart')[0];
  6. var items = [300, 80, 270, 90];
  7.  
  8. var total = 0;
  9. for (var i = 0; i < items.length; i++) {
  10. total += items[i];
  11. }
  12.  
  13. for (var i = 0; i < items.length; i++) {
  14. let value = Math.floor(map(items[i], 0, total, 0, 100));
  15. let item = chart.getElementsByClassName('item' + (i + 1))[0];
  16. item.style.width = value + '%';
  17. }

Although this works, it does cause the chart to flicker after the new widths have been applied to the elements. To make the transition a little easier for the user we can add a couple of new styles to the CSS so that the transition is animated.

  1. .chart div {
  2. height: 100%;
  3. float: left;
  4. transition-property: width;
  5. transition-duration: 0.5s;
  6. }

If you want to see of this code in action then I have created a codepen project with everything you need.

Making It Fully Dynamic

Taking it a step further it is possible to create a fully dynamic chart by adding a few more lines of JavaScript. This means that instead of being restricted to four items we can add as many items as we need. The first thing we need to do is remove the inner markup so that we can add in the chart items needed.

  1. <div class="chart">
  2. </div>

As we will be generating the inner components of the chart with all of the needed styles we can remove much of the existing styles for the chart. The chart CSS is now just a few rules.

  1. .chart {
  2. height: 2rem;
  3. width: 30rem;
  4. }
  5.  
  6. .chart div {
  7. height: 100%;
  8. float: left;
  9. transition-property: width;
  10. transition-duration: 0.5s;
  11. }
  12.  
  13. .chart .start {
  14. border-radius: 2rem 0 0 2rem;
  15. }
  16.  
  17. .chart .end {
  18. border-radius: 0 2rem 2rem 0;
  19. }

The new JavaScript code just needs to loop through the data we provide and create each item as the map is worked out. That item is then added to the chart, along with the needed styles to set a colour and correct width. A couple of if statements are also used to add extra classes for the start and end items in the chart.

  1. function map(value, valueRangeStart, valueRangeEnd, newRangeStart, newRangeEnd) {
  2. return newRangeStart + (newRangeEnd - newRangeStart) * ((value - valueRangeStart) / (valueRangeEnd - valueRangeStart));
  3. }
  4.  
  5. var chart = document.getElementsByClassName('chart')[0];
  6. var items = [300, 80, 270, 90, 100, 20, 160, 100];
  7. var colours = ['red', 'green', 'blue', 'yellow', 'cyan', 'orange', 'darkgreen', 'grey'];
  8.  
  9. var total = 0;
  10. for (var i = 0; i < items.length; i++) {
  11. total += items[i];
  12. }
  13.  
  14. for (var i = 0; i < items.length; i++) {
  15. let value = Math.floor(map(items[i], 0, total, 0, 100));
  16. const item = document.createElement('div');
  17. item.style.width = value + '%';
  18. item.style.backgroundColor = colours[i];
  19. if (i == 0) {
  20. item.classList.add('start');
  21. }
  22. if (i == items.length - 1) {
  23. item.classList.add('end');
  24. }
  25. chart.append(item);
  26. }

This code generates the following bar chart. The only limitation in this is the number of colours that are in the colours array as this currently dictates the length of the data items that can be shown. You can either increase the number of colours or simply loop around to the start of the colours list once the end is reached.

Horizontal segmented bar chart auto size

If you want to see the JavaScript generated bar chart in action then I have created a codepen project for that as well. Feel free to use this in your own projects.

What is missing from the above examples is the actual figures of the bar chart and some kind of label to show what the colours are. This is an important part of the chart as it will show what numbers belong to what colours. I will leave as an exercise for the reader as it all it needs is a table or an ordered list with some background colours applied.

Add new comment

The content of this field is kept private and will not be shown publicly.