šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

CSS Flexbox Bar Chart

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:
CSS Flexbox 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
    CSS Flexbox Bar Chart

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!

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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