{% extends "!layout.html" %}
{% block extrahead %}
{{ super() }}
<style type ="text/css">
div.sphinxsidebarwrapper {
  position: relative;
  top: 0px;
  padding: 0;
}
</style>
<script type="text/javascript">
  // intelligent scrolling of the sidebar content
  $(window).scroll(function() {
    var sb = $('.sphinxsidebarwrapper');
    var win = $(window);
    var sbh = sb.height();
    var offset = $('.sphinxsidebar').position()['top'];
    var wintop = win.scrollTop();
    var winbot = wintop + win.height(); // height for jQuery 1.4.2
    var curtop = sb.position()['top'];
    var curbot = curtop + sbh;
    // does sidebar fit in window?
    if (sbh < win.height()) { // height for jQuery 1.4.2
      // yes: easy case -- always keep at the top
      sb.css('top', $u.min([$u.max([0, wintop - offset - 10]),
                           $(document).height() - sbh - 200]));
    } else {
      // no: only scroll if top/bottom edge of sidebar is at
      // top/bottom edge of window
      if (curtop > wintop && curbot > winbot) {
        sb.css('top', $u.max([wintop - offset - 10, 0]));
      } else if (curtop < wintop && curbot < winbot) {
        sb.css('top', $u.min([winbot - sbh - offset - 20,
                             $(document).height() - sbh - 200]));
      }
    }
  });
</script>
{% endblock %}

Make sidebar sticky when scrolling
Make sidebar sticky when scrolling

Caution: window.height function might depends on jQuery version.
