Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Side bar that scrolls and then gets fixed

I have got a fixed sidebar but I would like my sidebar to scroll and then get fixed like here http://jessicahische.is/working/. Can this be done just with CSS?

2 Answers

James Barnett
James Barnett
39,199 Points

No CSS has no way of knowing the current position on the page you need JavaScript for that.

This code will do it for you:

$(function () {
    var sidebar = $('.sidebar');
    var top = sidebar.offset().top - parseFloat(sidebar.css('margin-top'));

    $(window).scroll(function (event) {
      var y = $(this).scrollTop();
      if (y >= top) {
      } else {

That code came from this very helpful article on how to create fixed floating elements, the article walks through what each line of the code does.

I made a quick demo on codepen using this technique that seems to approximate what the sidebar is doing on Jessica Hische's site.

Thanks James. This is awesome!