Monday, 8 January, 2024 UTC


Summary

For simple one-off visualizations, CSS Flexbox or CSS Grid can be great tools for rendering simple charts.
I thought it might be worth sharing how easy it is to make a small demo of implementing a basic bar chart using only CSS Flexbox.
By the end of the post, we will build the below table bar chart:
If you want to skip ahead here is the live example and the full code is on GitHub.
The bar chart is rendered using two nested flexbox layouts:
  • first, the overall chart is a flexbox layout with the row direction. This makes each item from the chart to be evenly-spaced along the horizontal axis
  • and each item entry within the chart is made as a flexbox layout with the column-reverse direction. This allows the "value" and the "bar" to float to the bottom of each entry in the vertical axis
The bar items from the chart have the following HTML markup:
<dl class="chart">
    <div class="item">
        <dt class="label"> Google </dt>
        <dd class="val">
            35
            <span class="bar" style="height: 35px;"></span>
        </dd>
    </div>
    <!-- rest of the bar items here -->
</dl>
And this is all the needed CSS:
.chart {
    border: 1px solid;
    display: flex ;
    gap: 1rem ;
    margin: 1rem;
    padding: 1rem;
}

.item {
    display: flex ;
    flex: 1 1 auto ;
    flex-direction: column-reverse ;
    gap: 5px ;
    height: 250px ;
}
.label {
    flex: 0 0 auto ;
}
.val {
    flex: 0 0 auto ;
    margin: 0;
}
.bar {
    background-color: var(--cl-main) ;
    border-radius: 5px;
    display: block ;
    margin-top: 8px ;
}
Is this the most robust bar char you've ever seen? Or the best solution? For sure not. But, there's no JavaScript involved and the layout is simple to understand. The main idea is that CSS Flexbox is awesome and it makes the web a better place!