Pure CSS Bar Graphs with Graceful Mobile Fallbacks
December 8, 2020
So in the end, this is what our bar graphs will look like on desktop:
And this is how it will look on smaller devices:
Let’s get into the details!
The main “secret” of this project is that our graphs are constructed out of HTML tables. Now before you freak out - this is perfectly fine and works in our favor quite well.
If the user has JS disabled –> they will still see our graphs
If the user has CSS disabled –> they will see a standard data table set
All bases are covered!
Nothing crazy is happening here - just your standard HTML table structure. The one main thing to notice is the --data-set CSS variable placed inline on each data point. This will be important for our CSS to configure the individual bar graphs properly.
This might look overwhelming if I just dumped the whole CSS file in one big code block, so instead I’m going to break them down into two parts:
Baseline styling (mobile)
Here we target just our table elements with the data-id of flexbox-bar-graph. This allows us to avoid worrying about adding classes or IDs and also avoids conflicts with other non-graph styled tables in our projects.
The base :root element holds all of our bar graph colors. Change these as you see fit!
Now we set your “visual” bar graphs to show at a set width (in this example it is 1000px and above). That way the “default” styling can target the mobile device screen sizes.
The thead tr th:nth-child(x):before elements create the square “legends” beside each individual data point heading
The tbody tr td:nth-of-type(x) span elements are the bars themselves
In the Flexbox Bar Graph repo, I’ve also included the ability to display these bar graphs horizontally, like so:
The change in CSS is actually quite simple to pull this off - you just need to include the data-layout attribute on the table itself.
That’s All Folks!
That just about sums things up. Feel free to check out the Github repo itself, open any issues you find or fork it for your own!