Animating And Transitioning CSS Custom Properties

This code animates a CSS property, and transitions a custom CSS property. The transition property is used in the animation. This combination works on Chrome, but unfortunately fails on Firefox and Safari.

See animation below, followed by the code snippet.

The Bar element should pulse, but at the start of the animation pulses should start at low opacity (similar to Foo) and slowly fade in, which is what happens on Chrome.

On Firefox and Safari the Foo element will fade in but the Bar element will pulse in the same manner no matter the transition state.

Foo

Bar

<style>
    @property --o {
        syntax: '<number>';
        inherits: false;
        initial-value: 0;
    }

    /* Test element so we can see that the custom property transition works */
    #foo {
        --o: 0;
        transition: --o 6s linear;
        background-color: rgba(0, 0, 0, var(--o));
    }

    #foo.in {
        --o: 1;
    }

    /* Element with transition and animation */
    #bar {
        --o: 0;
        transition: --o 6s linear;
    }

    #bar.in {
        --o: 1;
        animation: pulse 0.5s linear alternate infinite;
    }

    @keyframes pulse {
        from {
            background-color: rgba(0, 0, 0, 0);
        }

        to {
            background-color: rgba(0, 0, 0, var(--o));
        }
    }
</style>

<p id="foo">Foo</p>

<p id="bar">Bar</p>

<script>
    setTimeout(() => {
        foo.classList.add('in');
        bar.classList.add('in');
    }, 1000);
</script>

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

Or join my newsletter

More articles More articles