Use
posistion: sticky;
CSS:
#stickyunit {
position: sticky;
top: 57px;
}
You need the "top" element as well to define when the unit will start scrolling -
top: 0;
is approproate for most situations - but we have the 37px high sticky navigation menu by default on XenForo - so I had to make it start scrolling at 57px from the top to allow for the nav menu plus a 20px margin.
You also need to ensure that the ad container is a "sibling" of the other elements in the sidebar (the widgets), because it needs to scroll inside the parent container (the sidebar), so don't wrap your container with another div - make sure the outer div is a
<div class="block"
element like the widgets are.
So it's not your ad div that you stick, it's the container above it, which is a sibling of the widgets (which all use
<div class="block"
containers)
HTML:
<div class="block" id="stickyunit">
<div class="my-ad-class" style="width: 300px; height: 600px;">
<!-- ad code goes here -->
</div>
</div>
Here is an article which explains why this is necessary:
https://elad.medium.com/css-position-sticky-how-it-really-works-54cd01dc2d46