Home > Net >  Interaction of transparent elements with background-attachment: fixed
Interaction of transparent elements with background-attachment: fixed

Time:12-02

Why is the div "transparent-area" not showing the fixed background-image? MDN says that "[...] a background image's position is fixed within the viewport [...]", so I did assume any transparent parts of the website would make the background visible again.

<div id="background"></div>
<div id="first-section">A B C D E F</div>
<div id="transparent-area"></div>
<div id="second-section">G H I J K L</div>
#background {
  height: 100vh;
  background-image: url("https://images.unsplash.com/photo-1612225330812-01a9c6b355ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2670&q=80");
  background-size: cover;
  background-attachment: fixed;
  background-repeat: no-repeat;
}

#first-section {
  height: 300px;
  background-color: #000033;
}

#second-section {
  height: 300px;
  background-color: #000033;
}

#transparent-area {
  height: 300px;
}

Fiddle: https://jsfiddle.net/t4sdpy6g/14/

CodePudding user response:

The question asks why the transparent div does not show the background of the first div.

The answer is that the first div has scrolled out of view.

The first div has not been fixed in the viewport. Only its background has been fixed in position - it isn't going to 'stay behind' as the div gets scrolled out of view.

You can see this if you remove the other divs but put the first one into a very tall div and scroll.

You can also see it if you use a pre IOS15 version of Safari - these did not support background-attachment and the background begins to scroll out of view immediately.

If what you want is for a sort of parallax effect where the bacground image stays fixed while others scroll over it make the first div the wrapper of the others in the way the answer from @alejskorovin shows.

CodePudding user response:

You could change a bit your markup and styles and make your #background as a wrapper with a padding 100vh. Please check the example below (https://codepen.io/alekskorovin/pen/zYEGxjd):

#background {
  padding-top: 100vh;
  background-image: url("https://images.unsplash.com/photo-1612225330812-01a9c6b355ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2670&q=80");
  background-size: cover;
  background-attachment: fixed;
  background-repeat: no-repeat;
}

#first-section {
  height: 300px;
  background-color: #000033;
}

#second-section {
  height: 300px;
  background-color: #000033;
}

#transparent-area {
  height: 300px;
}
<div id="background">
  <div id="first-section">A B C D E F</div>
  <div id="transparent-area"></div>
  <div id="second-section">G H I J K L</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related