Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS

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) {
        sidebar.addClass('fixed');
      } else {
        sidebar.removeClass('fixed');
      }
    });
});

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!