Introduction
Animating text color in CSS allows for smooth transitions between different colors, creating eye-catching effects for headers, buttons, or highlighted text. This effect can be achieved using @keyframes
along with the color
property.
In this tutorial, you'll learn how to animate text color changes using HTML and CSS.
Problem Statement
Create a CSS code that:
- Animates text to smoothly transition between different colors.
- Demonstrates how to control the duration and repetition of the color change animation.
Example:
- Input: A heading element with the text "Color Changing Text".
- Output: The text color transitions between different colors continuously.
Solution Steps
- Use
@keyframes
for Color Change Animation: Define keyframes to animate thecolor
property. - Apply the Animation to Text: Use the
animation
property to control the color change duration and repetition.
HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Color Change Animation</title>
<style>
/* Step 1: Define keyframes for color animation */
@keyframes colorChange {
0% {
color: #3498db; /* Blue */
}
25% {
color: #e74c3c; /* Red */
}
50% {
color: #f1c40f; /* Yellow */
}
75% {
color: #2ecc71; /* Green */
}
100% {
color: #3498db; /* Back to Blue */
}
}
/* Step 2: Apply color animation to text */
.color-changing-text {
font-size: 3rem;
font-family: Arial, sans-serif;
text-align: center;
animation: colorChange 5s infinite; /* 5-second animation, infinite loop */
margin-top: 100px;
}
/* Center the text */
.container {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h1 class="color-changing-text">Color Changing Text</h1>
</div>
</body>
</html>
Output
Explanation
Step 1: Define @keyframes
for Color Animation
The
@keyframes
rule defines how the color changes over time:@keyframes colorChange { 0% { color: #3498db; /* Blue */ } 25% { color: #e74c3c; /* Red */ } 50% { color: #f1c40f; /* Yellow */ } 75% { color: #2ecc71; /* Green */ } 100% { color: #3498db; /* Back to Blue */ } }
At
0%
, the text is blue, then transitions through red, yellow, and green, before returning to blue at100%
.
Step 2: Apply Color Change Animation to Text
To apply the color change animation, use the
animation
property:.color-changing-text { animation: colorChange 5s infinite; }
The
5s
specifies the duration of the entire animation cycle, andinfinite
ensures the animation continues to loop.
Step 3: Center the Text for Better Display
- Use
text-align: center
to center the text on the page and add some margin for spacing:.container { text-align: center; }
Conclusion
Animating text color changes in CSS is easy using @keyframes
and the color
property. This effect allows you to create smooth transitions between multiple colors, adding a dynamic visual element to your web page.
Comments
Post a Comment
Leave Comment