Open In App

How to Create a Sliding Background Effect Using CSS ?

Last Updated : 08 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A sliding background effect in CSS creates a smooth, continuous movement of a webpage’s background image, typically in a horizontal or vertical direction. It gives a dynamic, animated feel by using properties like background-position and animation, enhancing visual engagement without additional JavaScript.

Approach

  • Container Setup: The .wrapper class ensures content overflow is hidden, creating a viewport for the sliding background animation.
  • Background Configuration: The .sliding-background class applies a repeating background image, with dimensions set to create the sliding effect.
  • Animation Definition: The @keyframes slide defines the animation movement from the initial to final background positions along the x-axis.
  • Animation Properties: The animation property applies a smooth, continuous movement lasting 60 seconds, using a linear timing function for constant speed.
  • Infinite Loop: The infinite keyword in the animation property ensures the sliding background effect repeats endlessly without interruption.

Example: In this example we are following above-explained approach.

html
<!DOCTYPE html>
<html>

<head>
    <title>Sliding Background</title>
    <style>
        .wrapper {
            overflow: hidden;
        }

        .sliding-background {
            background: url(
"https://media.geeksforgeeks.org/wp-content/uploads/20241008160354095180/gfg-d.png") 
            repeat-x;
            height: 961px;
            width: 6000px;
            animation: slide 60s linear infinite;
        }

        @keyframes slide {
            0% {
                transform: translate3d(0, 0, 0);
            }

            100% {
                transform: translate3d(-2000px, 0, 0);
            }
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="sliding-background"></div>
    </div>
</body>

</html>

Output:

SlA

Sliding background Effect using CSS Example Output



Next Article

Similar Reads