I have a very simple code , but in this code , position sticky property of CSS is not working as expected , please help
HERE is the html code
<div class="parent">
<div class="child1">
</div>
<div class="child2">
<div class="first">SOME </div>
<div class="last">AND THERE</div>
</div>
</div>
HERE IS THE Css code
.parent {
display: flex;
align-items: flex-start;
}
.parent >* {
width: 100%;
}
.child1 {
height: 1000vh;
background-color: cyan;
}
.child2 {
background-color: bisque;
position: relative;
}
.child2 > *{
border: 5px solid black;
}
.first {
height: 500px;
}
.last {
background-color: grey;
position: sticky;
top: 0;
height: 500px;
}
I expected the last div will stick to the top when i comes in contact with top of the screen , but it’s not happening
2
Answers
You have to remove
align-items: flex-start;
to keep the default stretch alignment and make sure the child2 is as tall as child1 to have a sticky behavior inside itFor "position:sticky" to work you need a high enough parent. In your case you need to set your .child2 height to:
a) considerably more than the combined children’s height;
b) a value that answers the question "how much do you want the div to stick around?". If you want it all the way to the bottom of the page, .as child1 has 1000vh height, you’d need that as well for .child2
You can also drop the position:relative on .child2. It does nothing.
The code snippet uses a height of 1000vh. Change that as you please.