Сделал так:
<div class="row">
<div class="col-auto d-flex">
<div class="sticky">
...
</div>
</div>
<div class="col">
...
</div>
</div>
.top-0 {
top: 0 !important;
}
.bottom-0 {
bottom: 0 !important;
}
.left-0 {
left: 0 !important;
}
.right-0 {
right: 0 !important;
}
'use strict';
$(document).ready(function() {
let $window = $(window);
let stick = (function () {
let $sticky = $('.sticky');
let $stickyParent = $sticky.parent();
let windowTopPrevious = 0;
$stickyParent.addClass('align-items-start');
$sticky.addClass('position-sticky top-0');
return function () {
let $windowHeight = $window.height();
let windowTop = $window.scrollTop();
let windowBottom = windowTop + $windowHeight;
let stickyTop = $sticky.offset().top;
let $stickyHeight = $sticky.outerHeight();
let stickyBottom = stickyTop + $stickyHeight;
let stickyTopRelativeParent = $sticky.position().top;
let stickyBottomRelativeParent = stickyTopRelativeParent + $stickyHeight;
if ($windowHeight >= $stickyHeight) {
if (!$sticky.hasClass('top-0')) {
$stickyParent.removeClass('align-items-end').addClass('align-items-start');
$sticky.removeClass('bottom-0').addClass('top-0');
}
} else if (windowTop > stickyTop || windowBottom < stickyBottom) {
if (windowTop > windowTopPrevious) {
if ($sticky.hasClass('top-0')) {
$sticky.css('margin-top', stickyTopRelativeParent + 'px').removeClass('top-0');
}
if (windowBottom > stickyBottom && !$sticky.hasClass('bottom-0')) {
$stickyParent.removeClass('align-items-start').addClass('align-items-end');
$sticky.css('margin-top', '0').addClass('bottom-0');
}
} else if (windowTop < windowTopPrevious) {
if ($sticky.hasClass('bottom-0')) {
$stickyParent.removeClass('align-items-end').addClass('align-items-start');
$sticky.css('margin-top', stickyTopRelativeParent + 'px').removeClass('align-self-end bottom-0');
}
if (windowTop < stickyTop && !$sticky.hasClass('top-0')) {
$sticky.css('margin-top', '0').addClass('top-0');
}
}
}
windowTopPrevious = windowTop;
}
})();
if ($window.scrollTop() > 0) {
stick();
}
$window.on({
'scroll': stick
});
});