If you are using React I recently published a custom hook which enables you to do this. You need to supply a ref to the sticky element as well as a ref to the element you want it to stick to the top of. It handles the screen "jump" (as mentioned in other responses) for you as well.
const sticky = useRef<HTMLDivElement>(null)
const container = useRef<HTMLDivElement>(null)
useStickyScroll({
element: sticky,
container: container
})