0

I was wondering if it's possible to nest a CSS Variable within a CSS variable's name or possibly do something similar:

:root {
  --color-1: red;
  --index: 1;
}

span {
  color: var(--color-var(--index))
}
3
  • 1
    What happened when you tried it? Where/how is --color-var defined? Commented Apr 10, 2024 at 8:17
  • See the specs, not possible with vanilla CSS. If you have tested and verified this with an example you could have seen this is invalid with the developer tools as well Commented Apr 10, 2024 at 8:21
  • it seems you want a kind of array, check this:css-tip.com/color-switch-color-mix and this:css-tip.com/colors-array Commented Apr 10, 2024 at 8:59

1 Answer 1

1

Nesting CSS variables directly within another variable's name, as in your example, is not possible with plain CSS. CSS variables (custom properties) cannot be dynamically constructed by concatenating strings or other variables within the var() function.

Some alternative approaches to achieve similar dynamic theming or styling effects could be using JavaScript, CSS Preprocessor(Sass or Less) or CSS-in-JS Solutions.

A JavaScript example:

let index = 1; // Assume this is dynamically changed somewhere in your app

document.documentElement.style.setProperty('--dynamic-color', `var(--color-${index})`);
:root {
  --color-1: red;
  --color-2: blue;
  /* Define more colors as needed */
}

span {
  color: var(--dynamic-color);
}
<span id="dynamicSpan">This is a dynamic color span</span>

In the above example the JS sets the --dynamic-color variable based on the index value. Whenever you change the index, you would need to run the setProperty line again to update the color.

I hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.