Brian O'Neill
Brian O'Neill

Reputation: 5185

Parallax scrolling: How can I make the parent height shrink to fit the content?

I'm trying to create a parallax scrolling effect for an article. Here is my HTML: a main-wrap div containing an article and a footer. The article's height should always match that of the vertical space its children occupy.

<div class="main-wrap">

  <article>

    <div class="hero">
      <div class="hero__content"> 
        <!-- content here --> 
      </div>
    </div>

    <div class="content"> 
      <!-- content here --> 
    </div>

  </article>

  <footer> 
    <!-- content here --> 
  </footer>

</div>

Now, with jQuery, I'm adding these parallax effects:

$(window).scroll(function(){

   var scrollPos = $(this).scrollTop();

   // parallax the hero text in fromt of the background image
   $('.hero__content').css({
      'top' : (225-(scrollPos*.2)) + 'px'
   });


   // parallax the article-content in front of the hero
   $('.content').css({
      'top' : (0-(scrollPos*.5)) + 'px'
   });

});

The parallax part is working fine. The problem is that the I need the height of the article to shrink. Otherwise, there is blank space at the bottom of the article.

I created a CodePen here: http://codepen.io/anon/pen/XmrLxJ The article is given a red background color to show the extra spacing. I've tried giving the article element CSS height properties of "inherit" and "auto," but that's not working.

Upvotes: 0

Views: 1054

Answers (1)

Mark E
Mark E

Reputation: 3483

T.L. D.R. Change the line 'top' : (0-(scrollPos*.5)) + 'px' for 'margin-top' : (0-(scrollPos*.5)) + 'px'
Your problem is that you are changing the position of the element with javascript and since it has a relative position the element is moved from its original position but the original position is still acquainted when rendering the rest of the document. To solve this you can animate a property which moves the element in the document instead of just moving where it is displayed. I don't know if I made myself clear but you if you change the property being animated from topto margin-topit works.

But imho the animation of .article-content is hardly noticeable. I removed it in you code pen and couldn't notice the difference.

Just as a foot note, I use this library for scroll effects and I have found it pretty useful and easy to use.
http://prinzhorn.github.io/skrollr/

Upvotes: 1

Related Questions