DEV Community

Cover image for How to move background image on scroll
Stackfindover
Stackfindover

Posted on • Updated on

How to move background image on scroll

Hello, guys in this tutorial we will make an awesome move background image on scroll

Common Query

  1. How to move background image on scroll
  2. How to add background move animation on scroll
  3. How to create background animation
  4. move div on scroll

Hello, guys In this tutorial we will try to solve above mention query. and also we will learn how to move background image on scroll

First, we need to create three files index.html and style.css then we need to do code for it.

Step:1

Add below code inside index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>How to move background image on scroll</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
  <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@500&display=swap" rel="stylesheet"> 
</head>
<body>
  <div class="section bg-static">
    <div class="move"></div>
  </div>
  <div class="content">
    <h1>Move background image on scroll</h1>
  </div>
  <script>
    $(window).on("load resize scroll", function() {
    $(".bg-static").each(function() {
      var scrollTop = $(window).scrollTop();
      var elementTop = $(this).offset().top;
      var leftPos = scrollTop - elementTop;
      $(this)
        .find(".move")
        .css({ left: leftPos });
      });
    });

  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step:2

Then we need to add code for style.css which code I provide in the below screen.

* {
    padding: 0;
    margin: 0;
    font-family: 'IBM Plex Sans', sans-serif;
} 
body {
    width: 100%;
    height: 200vh;
    overflow-x: hidden;
}
.bg-static {
    position: relative;
    max-width: 100%;
    min-height: 100vh;
    background-image: url("01.jpg");
    background-size: cover;
    background-position: center;
  }
.move {
    position: absolute;
    top: 0;
    bottom: 0;
    right: auto;
    width: 100%;
    background-image: url("02.png");
    background-size: cover;
    background-position: center;
}  
.content {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Spotlight Cursor Text Screen

CSS Toggle Switch

Move background on scroll Video output:

Latest comments (0)