Categories
CSS Web development

CSS background-attachment Property

CSS background-attachment Property

The CSS background-attachment property settles whether a background image is fixed or scrolls with the rest of the page.

Demo:

Syntax:

background-attachment: scroll|fixed|local;

scroll (default) – the background image scrolls with the page.

fixed – the background image won’t scroll with the page.

local – the background image scrolls with the element’s contents.

Example1: Scroll

<!DOCTYPE html>
<html>
<head>
<style> 
body {
  background-color: #fec5bb;
  background-image: url("https://lenadesignorg.files.wordpress.com/2020/02/heart.png?w=640");
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: scroll;
  height: 200vh;
}
</style>
</head>
<body>

<h1 style="text-align:center;">The background Property</h1>
<h3 style="text-align:center;">Scroll down to see the effect</h3>

</body>
</html>

Output:

Example2: Fixed

<!DOCTYPE html>
<html>
<head>
<style> 
body {
  background-color: #fec5bb;
  background-image: url("https://lenadesignorg.files.wordpress.com/2020/02/heart.png?w=640");
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: fixed;
  height: 200vh;
}
</style>
</head>
<body>

<h1 style="text-align:center;">The background Property</h1>
<h3 style="text-align:center;">Scroll down to see the effect</h3>

</body>
</html>

Output:

By using CSS background-attachment property (fixed) you can create a parallax scrolling effect (create an illusion of 3D depth):

*to see the CSS parallax scrolling effect tutorial click here.

Enjoy coding!