Leon Laci Leon Laci - 6 months ago 34
Javascript Question

Simple parallax effect with fixed content

I have a simple parallax effect, background image with fixed background attachment. The parallax effect is on the jumbotron(does it have a different name?), and on the jumbotron I have content like heading, subheading and a button. How can I make it so when I scroll the jumbotron content stays in place so it will have the effect of content below jumbotron like it is moving over it.

I have seen this types of effects but it isn't very common so it is hard for me to find an example, I hope you understood my description.



.jumbotron {
background-image: url(http://placekitten.com/1920/1080);
background-size: cover;
background-attachment: fixed;
text-align: center;
padding: 40px 10px;
color: blue;
}

<section class="jumbotron">
<h1 class="title">Title</h1>
<h2 class="subtitle">Subtitle</h2>
<p class="description">Lorem ipsum dolor sit amet...</p>
<a href="#" class="button">Button</a>
</section>




Answer

You'll have to do this via position:fixed; and some clever use of the z-index.

Here's a fiddle of what you were trying to achieve: https://jsfiddle.net/n4ebgmo7/1/

And here is the fixed CSS:

.jumbotron {
  background-image: url(http://placekitten.com/1920/1080);
  background-size: cover;
  background-attachment: fixed;
  text-align: center;
  padding: 40px 10px;
  color: blue;
  position: fixed;
  z-index: 1;
  width: 100%;
  top: 0;
}

.content {
  position: relative;
  z-index: 2;
  background-color: #ffffff;
  margin-top: 250px;
  width: 100%;
  padding: 1em;
}

What you are essentially doing here is fixing the .jumbotron to the top of the page, and telling the element below it, that it must:

  1. Be higher than the .jumbotron (this is done with the z-index)
  2. have a margin-top equal to the height of the .jumbotron so that it does not start on top of the .jumbotron

Edit

If the height of the .jumbotron is dynamic (as asked in the comment) then you can affix a little bit of jQuery to dynamically set the margin-top of your .content section.

Here is a fiddle showing you how: https://jsfiddle.net/n4ebgmo7/3/

Here is the needed jQuery:

$(document).ready(function(){
    $('.content').css({
    'margin-top':$('.jumbotron').outerHeight()
  });
});