Create simple graph with css flexbox

When I first read about flexbox I was quite sceptical because I thought that this would be poorly executed and the developers would have to hack around several things.
But I was delighted to be wrong… flexbox seems quite promising and it actually makes creating a simple timeline graph a 5 minute procedure.

For those unfamiliar with the CSS Flexbox spec here are some cool resources:

Now onward to our little project.

What we are trying to achieve here is to create a “timeline” based block-graph.

This is the end result:

See the Pen Flexbox graph by Michael Dobekidis (@netgfx) on CodePen

Let’s break down each piece.

HTML Markup

<div class="flexContainer">
  <div class="graphItem pink"></div>
  <div class="graphItem yellow"></div>
  <div class="graphItem blue"></div>
  <div class="graphItem green"></div>
  <div class="graphItem red"></div>
  <div class="flexTimeline">

We add a single container, and some children that would be the graph-bars (each one has a class that shows the bar background-color)

CS Style

Now lets get to the juice of this:




  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  flex-flow: row wrap;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  justify-content: space-around;
  border-top:2px solid #fff;
   -webkit-flex-flow: row wrap;



  /*border-left:2px solid #ffffff;*/








What we have done here is to declare the main container as a flexbox with

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;

But the really important code is the following:

-webkit-flex-flow: row wrap;

Which means that the children of the container will stretch to fill the available space.

So if we combine this functionality with the children percentages, we have a fully responsive graph.

Now lets add some javascript to complete the timeline feature.

Javascript flavor

  var time = new Date();
  var startTime = new Date('1/1/2007');
  var dif = time.getTime() - startTime.getTime();
  dif = Math.round(dif / 1000);
  dif = Math.round(dif / 60);
  dif = Math.round(dif / 60);
  dif  = Math.round(dif / 24);
  dif = Math.round(dif / 30);
  dif  = Math.round(dif / 12);
  for(var i=0;i<dif; i++){
    var result = Number(2007 + i);
    var parent = $(".flexTimeline");
    parent.append('<div class="timelineItem" >'+result+'</div>');


This simply creates a nice timeline bar to complete the looks of our graph.

Tagged , , , . Bookmark the permalink.

Leave a Reply

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