Search code examples
csscss-variables

Logging when a CSS variable not found


Is there a way to make a browser log events, when a CSS variable is not found? I'm wondering, because it seems to be useful for debugging. Say, if I have the following code:

.stroked-text
{
    /* Values to define in-place:

    --stroked-text-color-1
    --stroked-text-color-2
    --stroked-text-color-3
    --stroked-text-color-bg

    */

    --gradient: 320deg,
        var(--stroked-text-color-1) 5%,
        var(--stroked-text-color-2) 50%,
        var(--stroked-text-color-3) 90%;
    background: linear-gradient(var(--gradient));
    background-clip: text;
    -webkit-text-stroke: 3px transparent; /* No non-prefixed version. */
    color: black;
}

I want to be sure --stroked-text-color-1 is defined without the UI being visually checked. Logging would do the thing.

Of course, I can use the fallbacks mechanism like this:

var(--stroked-text-color-1, red) /* RED to to attract attention! */

but it also requires visual checking and in some cases there are no obviously wrong values.


Solution

  • There really isn't anyway to make logging in CSS. But i'm pretty sure you can use javascript here.

    function checkCSSVariableExists(element, variableName) {
        const value = getComputedStyle(element).getPropertyValue(variableName);
        if (!value) {
            console.warn(`CSS Variable "${variableName}" does not exist`);
        }
    }
    
    const element = document.querySelector('.stroked-text');
    checkCSSVariableExists(element, '--stroked-text-color-1');
    

    This should work if using JS is part of your options.