If you want to dynamically set fill colors using CSS variables/custom properties, you can achieve that easily. The var()
function's second argument allows you to specify a fallback/default value if the CSS variable is not defined.
For instance, if you wish to customize the start and end fill colors of #loading
, you can do so like this:
@keyframes changing {
0% {
fill: var(--loading-fill-from, rgb(105,105,105));
width: 20px;
}
100% {
fill: var(--loading-fill-to, rgb(250,230,0));
width: 200px;
}
}
This code defines the changing
keyframe with default fill colors of rgb(105, 105, 105)
for the start and rgb(250, 230, 0)
for the end. It also allows optional customization through --loading-fill-from
and --loading-fill-to
custom properties.
You can set these custom properties on the root element since CSS variables are inheritable:
document.documentElement.style.setProperty('--loading-fill-from', YOUR_COLOR_HERE);
Below is a proof-of-concept example (written in ES6 JS, but adaptable to TypeScript):
const varNames = ['loading-fill-from', 'loading-fill-to', 'loading2-fill-from', 'loading2-fill-to'];
document.querySelector('#btn').addEventListener('click', () => {
for (let varName of varNames) {
document.documentElement.style.setProperty(`--${varName}`, document.querySelector(`#${varName}`).value);
}
});
#loading {
animation-name: changing;
animation-duration: 4s;
animation-direction: alternate;
animation-iteration-count: infinite;
}
@keyframes changing {
0% {
fill: var(--loading-fill-from, rgb(105,105,105));
width: 20px;
}
100% {
fill: var(--loading-fill-to, rgb(250,230,0));
width: 200px;
}
}
#loading2 {
animation-name: changing2;
animation-duration: 4s;
animation-direction: alternate;
animation-iteration-count: infinite;
}
@keyframes changing2 {
0% {
fill: var(---loading2-fill-from, rgb(105,105,105));
width: 20px;
}
100% {
fill: var(--loading2-fill-to, rgb(13,255,191));
width: 200px;
}
}
<form>
<fieldset>
<legend>#loading</legend>
<label>
Loading button fill from:
<input type="color" id="loading-fill-from" value="#005f73"/>
</label>
<label>
Loading button fill to:
<input type="color" id="loading-fill-to" value="#94d2bd" />
</label>
</fieldset>
<fieldset>
<legend>#loading2</legend>
<label>
Loading2 button fill from:
<input type="color" id="loading2-fill-from" value="#f07167" />
</label>
<label>
Loading2 button fill to:
<input type="color" id="loading2-fill-to" value="#fed9b7" />
</label>
</fieldset>
<button type="button" id="btn">Change color</button>
</form>
<svg id="loading" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" /></svg>
<svg id="loading2" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" /></svg>