Matt B Matt B - 2 months ago 5
CSS Question

Make a div scroll with page only in a certain place?

How can it be made so that a div scrolls with the page but only in a certain area of the page?

I can't work out how to do this with CSS for only part of the page, I think javascript may be the only option.

For e.g. There's three sections of a page, Top, Middle and Bottom.

There's a right floated div which should scroll with the user in the middle section and stop scrolling to be 'left in place' at the top of the middle section as well as the bottom of the middle section.



#Top {
background-color: grey;
width: 100%;
height: 400px;
}
#Middle {
background-color: green;
width: 100%;
height: 800px;
}
#Bottom {
background-color: blue;
width: 100%;
height: 400px;
}
#scrolling-section {
background-color: yellow;
width: 30%;
height: 150px;
float: right;
}

<div id="Top">
</div>
<div id="Middle">
<div id="scrolling-section">
This box should scroll along the green section but 'cut-off' and stop scrolling at the top and bottom of the green section
</div>
</div>
<div id="Bottom">
</div>





JSFiddle: fiddle

Answer

So here you have solution using jquery:

  1. Listen to the scroll event and calculate how much the scrolling-section goes outside the Middle section while scrolling up / down.

  2. Added position: relative to the scrolling-section.

  3. Adjust the position of the scrolling-section accordingly.

$(document).scroll(function() {
  var wrapper = $('#Middle');
  var box = $('#scrolling-section');

  var offsetTop = - wrapper.offset().top + $(window).scrollTop();
  var offsetBottom = wrapper.offset().top - $(window).scrollTop() + wrapper.outerHeight() - box.outerHeight();

  if (offsetBottom > 0 && offsetTop < 0) {
    box.css({
      'top': 0
    });
  } else if (offsetBottom > 0 && offsetTop > 0) {
     box.css({
      'top': offsetTop + 'px'
    });
  } else {
    box.offset({
      'top': $(window).scrollTop() + offsetBottom
    });
  }

});
#Top {
  background-color: grey;
  width: 100%;
  height: 400px;
}
#Middle {
  background-color: green;
  width: 100%;
  height: 800px;
}
#Bottom {
  background-color: blue;
  width: 100%;
  height: 400px;
}
#scrolling-section {
  position: relative;
  background-color: yellow;
  width: 30%;
  height: 150px;
  float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Top">
</div>
<div id="Middle">
  <div id="scrolling-section">
    This box should scroll along the green section but 'cut-off' and stop scrolling at the top and bottom of the green section
  </div>
</div>
<div id="Bottom">
</div>

Let me know your feedback on this. Thanks!