When using position: sticky
on an element, the element sticks at the position I want in the window.
But when an ancestor has any overflow
value set (scroll
, hidden
, or auto
) other than visible
, the element suddenly doesn't stick anymore.
Here's a CodePen with an example. Try to remove and add overflow: scroll
on main
in CSS.
main {
overflow: scroll;
background: #eee;
min-height: 200vh;
display: flex;
flex-direction: column;
}
header {
background: lightblue;
flex: 2;
}
.sticky {
position: sticky;
top: 0;
background: pink;
flex: 1;
}
footer {
background: lightyellow;
flex: 2;
}
<html>
<head>
<title>Sticky</title>
</head>
<body>
<main>
<header>Hello</header>
<div class="sticky">I'm sticky</div>
<footer>I'm the footer</footer>
</main>
</body>
</html>
I want to understand why it behaves like this. I know the result, but I don't understand why. I tried to read the MDN documentation which talks about scrolling context, but I didn't get it. Do someone can explain it easily according to the CSS spec?