If you're looking for a way to dynamically change the color of elements on your website, I suggest using CSS variables, also known as custom properties:
function randomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r},${g},${b})`;
}
const root = document.documentElement;
root.style.setProperty("--random-color", randomColor());
.element-1,
.element-2 {
background-color: var(--random-color);
}
<p class="element-1">Element 1</p>
<hr />
<p class="element-2">Element 2</p>
To set a default value for the custom property in your CSS file, you can do the following:
:root {
--random-color: rebeccapurple;
}
Ensure that your elements utilize this property by using the CSS var()
function:
.element-1,
.element-2 {
background-color: var(--random-color);
}
If you want to update the color based on certain conditions, you can use JavaScript's style.setProperty
method within an if statement:
if (condition) {
const root = document.documentElement;
root.style.setProperty("–random-color", randomColor());
}
For further insights on dynamically managing custom properties, check out this informative article.