I just found the answer here https://css-tricks.com/how-to-detect-when-a-sticky-element-gets-pinned/
As of today you do need to use javascript:
const el = document.querySelector(".myElement")
const observer = new IntersectionObserver(
([e]) => e.target.classList.toggle("is-pinned", e.intersectionRatio < 1),
{ threshold: [1] }
);
observer.observe(el);
#parent {
height: 2000px;
}
.myElement {
position: sticky;
top: -1px;
}
/* styles for when the header is in sticky mode */
.myElement.is-pinned {
color: red;
}
<div id="parent">
<br /> <br /> <br /> <br />
<div class="myElement">Hello!</div>
</div>
top: -1px
is very important because IntersectionObserver
detect “how much your element is visible on the screen”. e.intersectionRatio
correspond to the percent of “visibility” of your el
. So if you use top: 0px
then e.intersectionRatio
will always equal 1
and the class is-pinned
will never be added.