Andrew JD Hudson

Photo of Andrew JD Hudson

Displaying CSS variables in CSS Content

346

I often have the need to see the in-place value of the a CSS variable on the page to help me debug what I am working on. To be able to do this I need to use CSS counter-reset in combination with CSS counter() to display within CSS content on a before or after pseudo element.

This is for future me as I always need to look it up.

CSS

.blob {
    --hue: calc(10 * var(--index));

    background: hsl(calc(var(--hue) * 1deg) 100% 50%);

    /* the counter name must be of type <custom-ident>. See https://developer.mozilla.org/en-US/docs/Web/CSS/counter-reset and https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident 
    The second value must be an integer (i.e. cannot have a unit so 30deg would not work here).
    */
    counter-reset: hue var(--hue);

    &::after {
        /* apply the counter value to the css content property */
        content: counter(hue) "deg";
    }
}

HTML

<div class="blob" style="--index: 1"></div>
<div class="blob" style="--index: 2"></div>
<div class="blob" style="--index: 3"></div>
<div class="blob" style="--index: 4"></div>
<div class="blob" style="--index: 5"></div>

Output:

← Back to all blog posts Edit this post on Github
andrew jd hudson :) •