Open In App

How to Animate Gradient Background Smoothly Using CSS ?

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Animating gradient backgrounds smoothly using CSS means setting a gradient background and using transitions or keyframe animations to create gradual changes in colors, angles, or positions. This technique adds a dynamic and visually attractive effect to enhance the webpage’s design.

What is Gradients?

Gradients are smooth transitions between colors, used for depth and visual effects. In CSS, they are created using the background-image property with linear-gradient() or radial-gradient() functions to blend colors seamlessly.

Approach to animate gradient background smoothly

  • Create HTML Divs: Begin by creating an HTML structure with one more div than the number of gradients you want. The extra div serves as the main layer with all the colors, to which we’ll add the animation.
  • Define Background: Use linear-gradient() to create a gradient background for animation.
  • Set Animation: Apply animation with keyframes to transition the background smoothly.
  • Keyframes Setup: Use @keyframes to define the sliding animation from -25% to 25%.
  • Add Layers: Create multiple background layers with different animation durations for depth.
  • Positioning: Fix the backgrounds and adjust z-index to place them behind content.

Syntax

@keyframes animation_name {
keyframes-selector {
css-styles;
}
}

Example: Here we are following the above-explained approach.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0" />
    <style>
        body {
            display: grid;
            place-items: center;
            color: yellow;
        }

        .main__bg {
            background-image: linear-gradient(-60deg, #404258 50%, #6B728E 50%);
            animation: slide 3s ease-in-out infinite alternate;
            position: fixed;
            top: 0;
            bottom: 0;
            left: -50%;
            right: -50%;
            opacity: 0.5;
            z-index: -1;
        }

        .layer1 {
            animation-direction: alternate-reverse;
            animation-duration: 4s;
        }

        .layer2 {
            animation-duration: 5s;
        }

        @keyframes slide {
            0% {
                transform: translateX(-25%);
            }

            100% {
                transform: translateX(25%);
            }
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h2>
        Animate gradient background smoothly using CSS
    </h2>
    <div class="main__bg"></div>
    <div class="main__bg layer1"></div>
    <div class="main__bg layer2"></div>
</body>

</html>

Output:




Next Article

Similar Reads