Search code examples
cssvisual-studio-codesyntax-highlightingcss-variableshsl

How can I get color decorations for CSS variable references to work in VS Code?


I'm working on CSS custom properties and their modification. It seems that the best way to add/change the alpha channel to colors is to use hsl notation:

:root {
  --green: 120deg, 100%, 50%;
}

.box {
  background: hsl(var(--green), 0.5);
}

The problem with this approach is that VS Code doesn't recognize hsl(var(--green)) as color:

enter image description here

How can I get color property values using CSS variable references to have color decorations in VS Code? Would such a thing even be realistically feasible in general?


Solution

  • How can I get color property values using CSS variable references to have color decorations in VS Code? Would such a thing even be realistically feasible in general?

    I don't think such a thing is realistically feasible in general because what we're talking about here is a feature based on static analysis, and CSS custom properties (variables) are very much a runtime (dynamic) feature.

    Consider just the following:

    <style>.proof { background-color: var(--my-var) }</style>
    <!-- okay, so what decoration do you think should show above? -->
    <div style="--my-var: #ff00ff;" class="proof">hello</div>
    <div style="--my-var: #ffff00;" class="proof">hello</div>
    <div style="--my-var: #00ffff;" class="proof">hello</div>

    That's a very simple proof that variable references are evaluated at runtime. And there can be multiple different values evaluated from the cascade at runtime (and static analysis would show...?). Even further points can be made:

    <style>.proof { background-color: var(--my-var) }</style>
    <!-- okay, so what decoration do you think should show above? -->
    <div style="--my-var: #ff00ff;"><div class="proof">hello</div></div>
    <div style="--my-var: #ffff00;"><div class="proof">hello</div></div>
    <div style="--my-var: #00ffff;"><div class="proof">hello</div></div>

    That simple modification shows that the evaluation depends on the cascade.

    Okay, so the evaluated value from the variable reference depends on the cascade, is evaluated at runtime (it's also tracked at runtime for style-recalculations and repaints). VS Code- or any static analysis- can't reasonably show you anything.

    In fact, after I initially finished writing this post, I googled "github vscode issues color decorations css variable", and found [css] color decorators for CSS Custom Properties / Variables #173923 where one of the VS Code maintainers essentially says the same thing (link).