Logging when a CSS variable not found - Stack Overflow

admin2025-04-18  3

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.

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.

Share Improve this question asked Jan 29 at 15:39 ShtoleShtole 3572 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

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.

转载请注明原文地址:http://anycun.com/QandA/1744955568a89991.html