Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Perform Animation on the background-color property with CSS
The CSS background-color property can be animated using CSS animations and keyframes to create smooth color transitions. This technique is commonly used to create hover effects, attention-grabbing elements, and interactive visual feedback.
Syntax
selector {
background-color: initial-color;
animation: animation-name duration timing-function iteration-count;
}
@keyframes animation-name {
percentage {
background-color: target-color;
}
}
Example: Basic Background Color Animation
The following example demonstrates a continuous background color animation that transitions from yellow to maroon and back −
<!DOCTYPE html>
<html>
<head>
<style>
.animated-box {
width: 300px;
height: 200px;
background-color: yellow;
animation: colorChange 3s infinite alternate;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: bold;
margin: 20px;
}
@keyframes colorChange {
0% {
background-color: yellow;
}
50% {
background-color: orange;
}
100% {
background-color: maroon;
}
}
</style>
</head>
<body>
<div class="animated-box">Animated Background</div>
</body>
</html>
A rectangular box smoothly transitions between yellow, orange, and maroon colors in a 3-second cycle, alternating direction with each iteration.
Example: Hover-Triggered Animation
This example shows how to trigger background color animation on hover −
<!DOCTYPE html>
<html>
<head>
<style>
.hover-button {
width: 200px;
height: 60px;
background-color: #3498db;
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.5s ease;
margin: 20px;
}
.hover-button:hover {
animation: hoverColors 1s ease-in-out;
}
@keyframes hoverColors {
25% {
background-color: #e74c3c;
}
50% {
background-color: #f39c12;
}
75% {
background-color: #27ae60;
}
100% {
background-color: #9b59b6;
}
}
</style>
</head>
<body>
<button class="hover-button">Hover Me!</button>
</body>
</html>
A blue button that cycles through red, orange, green, and purple colors when hovered over, creating an engaging interactive effect.
Key Properties
| Property | Description |
|---|---|
animation-duration |
Controls how long the animation takes to complete |
animation-iteration-count |
Defines how many times the animation repeats |
animation-direction |
Sets whether animation alternates or repeats in the same direction |
animation-timing-function |
Controls the speed curve of the animation |
Conclusion
Background color animations add visual appeal and interactivity to web elements. Use keyframes to define color transitions and combine with timing functions for smooth, professional effects that enhance user experience.
Advertisements
