I have searched and analyzed the answer on this subject, but it is not really clear to me what is the optimal solution to solve this problem.
I was doing tests placing my predecessors display: initial
and it works perfectly, however what happens when you have a display: flex
whole thing breaks.
I have created a link to codesandbox for your analysis and how this can be easily fixed (if possible).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<div class="container">
<div class="app-content">
<div class="another-container">
<div class="card-sticky">
Sticky card
</div>
</div>
</div>
</div>
</body>
</html>
<style>
.container {
height: 200vh;
}
.card-sticky {
position: sticky;
top: 0;
}
</style>
Let's see what an element with
position: sticky
:Now let's see an image with what is happening with the parent element (
another-container
) and the child element (card-sticky
):The child element already occupies all the space of its parent!
This is because it
another-container
is a block element , it takes up as muchwidth
as it can, but we haven't specified theheight
, so it will take up whatever its child element takes up, so the child can't be moved within its container.How do I fix this?
Adding a
height
to the parent element, so that its child can scroll inside it:When reaching the end of
height
(100vh) the child element stops moving, since it has already reached the end of its parent element. In the beginning, the end of the parent was the same as the end of the child, but by making the parent element taller than the child element , it was able to move freely within its ancestor.That is, having multiple containers is not the cause , but the fact of not declaring a height greater than the content (or
height
) that the child occupies, which means that it cannot scroll inside the parent