DEV Community


Simple CSS Animation with Custom Properties

adamthedev profile image Adam the Dev ・2 min read

I was building out a 'stats' design that needed some animation depending on assigned percentage.

What we're building:

Alt Text

My usual solution would be to have a data attribute on the 'bar' elements and then trigger the animation with a JavaScript loop (looping through each of the individual bars)

After playing around a bit, I found a neat CSS solution. Which was to add an inline style to each of the 'bar' elements

Within the inline style, I declared a variable ( ie '--percentage: #%') which would still allow me render dynamically with PHP

I then used the 'var' CSS function to apply that percentage to the element with a pseudo class. (and animated the bars with a keyframe)

Here's an example of a stats item HTML

<div class="stats">
    <div class="stats__item">
    <span class="stats__percentage">27.5%</span>
    <div class="stats__bar" style="--percentage: 27.5%;"></div>
        <span class="stats__age">18-24</span>

Here's the CSS properties used to animate and apply the percentage

.stats__bar {
    width: 67px;
    height: 158px;
    margin: 10px 0;
    background: #d5634e;
    border-radius: 4px;
    overflow: hidden;
    position: relative;

.stats__bar:after {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0; // THIS IS WHAT WE'LL ANIMATE
    left: 0;
    right: 0;
    background: #433737;
    animation: barsIn 0.9s ease-in-out forwards; // CALLING THE KEYFRAME

@keyframes barsIn {
    0% {
        bottom: 0;
    100% {
        bottom: var(--percentage); // APPLYING THE PERCENTAGE

Just thought I'd share it to anyone that doesn't know how to do this my learn something and saves having to use unnecessary JS!

Click for a full YT walkthrough

Does anyone have a cleaner/more efficient solution??


Editor guide