I’m working on a web project where I have defined several colors using CSS variables (--primary-color
, --secondary-color
, etc.). I want to smoothly animate the change of these colors when hovering over specific elements.
Here’s a simplified structure:
:root {
--primary-color: #aaf;
--secondary-color: #faa;
}
.element {
background-color: var(--primary-color);
transition: background-color 0.3s ease;
padding: 20px;
display: inline-block;
cursor: pointer;
}
.element:hover {
background-color: var(--secondary-color);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Variable Color Animation Example</title>
</head>
<body>
<div class="element">Hover over me</div>
</body>
</html>
I’ve tried using transitions on the background-color property with CSS, as shown above. However, this approach doesn’t smoothly transition between different CSS variable values (--primary-color
to --secondary-color
). The transition happens abruptly.
What’s the best approach to achieve smooth color transitions using CSS animations or JavaScript? Any guidance or examples would be greatly appreciated!
Software Developer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.