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))
}
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!
--color-vardefined?