Simple Parallax Header

So these are everywhere. I've seen hundreds of different ways to pull them off, and each claims to be the definitive one. This is not that parallax effect. I set a goal for myself to accomplish an efficient, effective parallax header in 15 minutes or less. What follows is the fruit of that labor.

As usual, let's start with the barebones structure - the HTML.

html

<header>
  <h1>Basic Parallax</h1>
  <img class="parallax" src="https://dl.dropboxusercontent.com/u/17846948/codepen/sunset.jpg" />
</header>
<section class="body-copy">
  <p>Craft beer occupy PBR lo-fi. Seitan cold-pressed Tumblr locavore freegan deep v 90's Vice. Whatever Blue Bottle raw denim, Williamsburg Tumblr fashion axe viral craft beer keffiyeh. Flexitarian lomo Pinterest, retro narwhal fanny pack lo-fi disrupt
    photo booth street art DIY bitters chambray taxidermy. Fixie put a bird on it crucifix, food truck street art ugh Etsy bicycle rights disrupt wolf twee Pitchfork pickled Tumblr VHS. Vice shabby chic flannel locavore, tousled kale chips aesthetic chia
    cred next level yr banh mi migas PBR&amp;B ugh. Locavore dreamcatcher organic fashion axe normcore banh mi.</p>
  <p>Wes Anderson four dollar toast Carles, quinoa synth XOXO beard next level cred. Marfa taxidermy migas pork belly wayfarers meditation, Banksy cardigan yr sustainable normcore street art Pinterest direct trade before they sold out. Swag Marfa tilde Brooklyn
    mlkshk, cold-pressed Godard Echo Park messenger bag pug ugh keytar banjo Pinterest. Four loko High Life ethical direct trade. Meditation migas twee, 90's Godard pour-over Pinterest locavore stumptown chambray Echo Park beard McSweeney's ugh +1. Literally
    paleo chia, actually disrupt hoodie drinking vinegar pour-over. Lo-fi tilde Pitchfork +1 irony High Life trust fund, hoodie Austin.</p>
  <p>Truffaut jean shorts freegan, butcher lumbersexual sriracha seitan disrupt sartorial craft beer selfies literally. Jean shorts raw denim lo-fi plaid, messenger bag Odd Future fashion axe hella Helvetica Pitchfork McSweeney's fixie sriracha Carles. Artisan
    deep v +1, Austin keffiyeh meh church-key slow-carb VHS mustache. Keffiyeh before they sold out vegan, fanny pack fingerstache pork belly pickled try-hard gastropub swag. Art party try-hard four loko VHS, Etsy paleo meh sustainable whatever Truffaut
    normcore Portland tote bag chillwave Tumblr. Fixie Odd Future flexitarian quinoa, tousled wayfarers American Apparel +1 cray retro. Selfies migas Odd Future, vegan Tumblr gastropub locavore beard pork belly Neutra.</p>
  <p>Stumptown cold-pressed kogi authentic small batch Echo Park cliche High Life fanny pack actually blog, scenester ennui selvage. Bespoke flannel vegan drinking vinegar disrupt. High Life readymade tattooed 8-bit, Truffaut church-key tofu tousled four
    dollar toast Pinterest fixie. Bespoke Williamsburg 90's tote bag, seitan taxidermy four loko roof party chambray typewriter actually disrupt Marfa banjo +1. You probably haven't heard of them viral sriracha ugh, DIY before they sold out Tumblr cronut
    gluten-free paleo kitsch. Bicycle rights umami Truffaut, sustainable messenger bag cray flannel Marfa. Cred pickled fap street art, you probably haven't heard of them kogi retro.</p>
</section>

See the Pen Basic Parallax by Jesse Couch (@designcouch) on CodePen.

The only really important stuff is right up there at the top in the header. The .body-copy section is simply to create content that causes a scroll—so that you can actually see how pretty our effect is!

Now comes our CSS (actually, SCSS). Nothing too fancy here either—we're just setting everything up so that it looks nice. The real heavy lifting is done in our JS.

css

header {
  height:500px;
  overflow:hidden;
  position:relative;
  h1 {
    position:absolute;
    top:50%;
    width:100%;
    text-align:center;
    font-size:60px;
    font-family: 'Limelight', cursive;
    font-weight:900;
    line-height:60px;
    margin-top:-30px;
    color:white;
    text-shadow:4px 4px 0 rgba(0,0,0,.3);
  }
  #parallax {
    width:100%;
    height:auto;
    display:block;
  }
}
section {
  &.body-copy {
    max-width:600px;
    margin:50px auto 0 auto;
    font-family:helvetica neue,helvetica,arial,sans-serif;
    font-weight:200;
    p {
      margin: 0 0 20px 0;
      font-size:16px;
      line-height:22px;
    }
  }
}

See the Pen Basic Parallax by Jesse Couch (@designcouch) on CodePen.

Ok, that looks nice and simple.

Now, the basic principle of a parallax effect is that the "further" away an object is from the user, the slower it moves. This can be done by stacking many layers and moving them each at a different velocity to establish massive depth, or it can be more subtle like ours and simply involve two planes; the content and the image.

The normal speed for the page is established by the user's scroll, so the content plane is covered by that. We're going to move our image at a different speed by adjusting a negative top margin in real time during the scroll. Basically, we're going to be pushing the image down the page at half the speed that the user is scrolling at. This still allows the image to move up, but it goes up half as fast as everything else and allows the content to overtake it.

Here's our JS - with buku annotations to boot.

js

// keep in mind that this script is written to target images that are already at the very top of the page. It would need to be adjusted for images that are further down.

$(document).ready(function() {
// once the image loads, fire off the first function
  $('.parallax').load(function() {
// store targeted image
    var target = $(this);
// get the height of the image
    var parallaxHeight = target.height();
// calculate the offset needed to vertically center the image in its container 
    var initialOffset = parallaxHeight / 2;
// use the calculated offset to create a negative top margin that vertically centers the image
    target.css('margin-top', '-' + initialOffset + 'px');
    
// when the user scrolls, execute the parallax effect
    $(window).scroll(function() {
// get the current scroll distance from the top of the screen
      var windowScrollPosition = ($(window).scrollTop())/2;
// subtract the scroll position from the previously calculated offset
      var newParallaxOffset = (initialOffset - windowScrollPosition);
// as user scrolls, continuallly adjust the negative top margin on the image
      target.css('margin-top','-'+newParallaxOffset+'px')
    });
  });
});

See the Pen Basic Parallax by Jesse Couch (@designcouch) on CodePen.

Sweet. Feel free to pick that apart in the comments—like I said above, I wrote it in all of 15 minutes so there's likely some flaws. Without further delay, here's your demo!

demo

See the Pen Basic Parallax by Jesse Couch (@designcouch) on CodePen.

Hope you enjoy it. Feel free to repurpose for your own needs, or ask any questions you might have below in the comments. Later, coders.

Did I help you out?

Read More

20 Years for Zeldman.com  →

There are 9 comments. Add Yours.

A Note from the Moderator

Thanks for taking the time to comment! I'll respond as quickly as possible if necessary. In the meantime, please keep the following in mind:

  • All comments must be appropriate. I'll delete 'em if you get nasty.
  • Please allow for response time. I'm here as much as possible, but can't always respond as quickly as some would like.
  • Please stay on topic.
  • I don't work for free—if you want custom work, feel free to get in touch and I'll write up a quote!
  1. Matthias

    Matthias

    Aug 12, 2015

    Centering the image with jQuery is bad practice because it causes the image to quickly jump before the library is loaded.
    Moreover, using margins to do the parallax effect might not be the best idea because, triggering JS on something as frequently called as the scroll event being a very extensive operation, it would make more sense to use transform: translate3d(), it being hardware accelerated.

    Anyway, I'd suggest you to center the image using CSS and check out this article on smooth parallax effects because it explains everything much better than I do:
    https://medium.com/@dhg/parallax-done-right-82ced812e61c

    Reply to Matthias

    1. Jesse

      Jesse

      Sep 04, 2015

      Thanks, Matthias. As is stated both in the Codepen description and in this article, I wasn't aiming for a perfectly smooth, optimized parallax effect. This was a "code as fast as you can, see what happens" type deal. When actually developing a new feature, I typically do about 3-5 of these and approach the problem from multiple directions to see which is the best, and then I refine the best of them (which is when suggestions like yours would come into play). Thanks for the suggestion though - good thoughts!

  2. Geeky Swap

    Geeky Swap

    Jul 30, 2017

    It was very useful for me. Keep sharing such ideas in the future as well. This was actually what I was looking for, and I am glad to come here! Thanks for sharing such information with us.

    Reply to Geeky

  3. Brian

    Brian

    Feb 10, 2018

    Are you going to get back into updating the blog? I learned some good stuff on this site, and it's a great design - especially like the full width/height header with title background box, very cool.

    Reply to Brian

    1. Jesse

      Jesse

      Apr 12, 2018

      Having a full-time job in software, a wife and twelve kiddos has robbed me of my nerdy free time as of late. I do plan to get back to writing quite soon - my goal is to be regularly posting again by the fall. I'm glad I've been able to help you out!

  4. The structure of such combinations looks quite simple. However, this is used to correlate correctly those or other data.

    Reply to http://customresearchpapers.ws

  5. The title looks simple but quite competently because you need to be able to convey the essence of the issue under discussion in the article.

    Reply to www.custom-essay.ws/blog/master-e2-80-99s-thesis.html

  6. I think that it is not necessary to keep silent about your needs and it is worth expressing them quite clearly in order to understand what needs to be done to meet them.

    Reply to www.customcollegeessays.com/blog/indian-civilization-history-essay

  7. Simple and useful tutorial. I had also encountered this problem when I was compiling a source code. Now I understand how to do this right.

    Reply to Online