Signup/Sign In

How to create a parallax scrolling effect with CSS?

The parallax scrolling effect is used to create an illusion of depth for a 3D effect, having multiple layers of scrolling. The parallax effect is very popular in video games for years and now it is being used in web designing too.

It enhances the look of the website. In the parallax scrolling, the background element moves at a slower speed than the foreground element.

Using background-attachment property

The background-attachment property gives the actual effect to the webpage. Along with is, we need some other CSS properties too.

  • background-attachment : The fixed value is added to background-attachment to give the parallax effect to the webpage.
  • background-image : It is used to add the background image to the webpage.
  • background-position : It is used to position the background image to the center.
  • background-size : This property is used to scale the image so it fills the background.
  • background-repeat : The no-repeat value is added to it so that the images do not repeat in the background.

Example: Create a parallax scrolling effect using CSS

In this example, we are creating a parallax scrolling effect by using CSS properties.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<style>   
	  .container {
	  /* The image used */
	  background-image: url("https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1626423162-101156.png");
	  /* Set a specific height */
	  height: 500px;
	  /* Create the parallax scrolling effect */
	  background-attachment: fixed;
	  background-position: center;
	  background-repeat: no-repeat;
	  background-size: cover;
     }
	 .parallax {
	   background: #CCCCCC;
	 }   
</style>
<body>
    <h2> parallax scrolling effect</h2>
	<div class="container">
	</div>
	<div class="parallax ">
	  <h2> Scroll down to see effect </h2>
	  <h2> Scroll down to see effect </h2>
	  <h2> Scroll down to see effect </h2>
	  <h2> Scroll down to see effect </h2>
	  <h2> Scroll down to see effect </h2>
	  <h2> Scroll down to see effect </h2>
	  <h2> Scroll down to see effect </h2>
	  <h2> Scroll down to see effect </h2>
	</div>	
</body>
</html>

Output

Here is the output of the above program.

parallax scrolling effect

Example: Add Parallax Effect with customize height

We can also set the height of the background image to 100%. Here is another program with the parallax effect. The height of the background image is set to 100%.

Conclusion

In this tutorial, we have learned about the CSS properties used to add parallax scrolling effect to the webpage. It enhances the website with 3-D visual effects. Here we have explained it with simple examples.



About the author: