As mentioned in @ Script47, you will want to apply overflow-x as a CSS property to your element, as well as width (act as a viewport). Here's what your final CSS looks like:
.container { white-space: nowrap; overflow-x: scroll; width: 250px; position: relative; }
After that you need to change JS a bit. You still want to scroll the offset element of this element, but you also need to take into account the current scroll position.
(To clarify, if you pressed orange - which originally had an offset of 250px , after the animation, the offset for the orange would be 0px and black would be 250px . If you then press black , it will try to scroll to 250px , which is an orange element.)
The updated JS will look here:
jQuery(document).ready(function ($) { $(".scroll").click(function (event) { var current = $('.container').scrollLeft(); var left = $(this.hash).position().left; event.preventDefault(); $('.container').animate({ scrollLeft: current + left }, 200); }); });
Demonstration violin: https://jsfiddle.net/bpxkdb86/4/
For the script, I removed the physical white-space in HTML (to prevent divs from being split) using <!-- comments --> , and also added position: relative to the containing element (use position )
source share