I have read as much as I can cope with about position sticky in css, but it is not behaving the way I expect. Can somebody please explain?
Here is what I have so far:
#upper {
width: 200px;
height: 200px;
background-color: blue;
}
#middle {
width: 200px;
height: 200px;
background-color: yellow;
position: sticky;
left: 100px;
top: 100px;
}
#lower {
width: 200px;
height: 200px;
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sticky position</title>
<link rel="stylesheet" href="sticky.css">
</head>
<body>
<div id="upper"></div>
<div id="middle"></div>
<div id="lower"></div>
</body>
</html>
What I expect
A blue box top left.
An overlapping yellow box (top left of yellow box overlapping bottom right of blue box.
A red box below the blue box, with a gap of the size of a box.
What happens
The blue and red boxes are where I expect. The yellow box is shifted to the right as expected, but is not shifted vertically and does not overlap the blue box.
What I have discovered
If I change top:100; to top:300; in the css for middle, the yellow box moves down and overlaps with the red box, as I would expect.
4
Answers
I guess
position: absoulte
is what you are looking for:You should not use position to be sticky, instead by using absolute solves the issue.
Here is the code:
I have also added a top margin of 200px to the red box so that there is a gap of one box that you wanted.
PS. Position sticky is used when you want some element to stick to a location when scrolling a web page. You may have noticed that navigation bar of some websites remains on the top of the page even if you are scrolling down, in this case position sticky is used.
Perhaps what you really want is to have the yellow positioned relative to the other elements from its natural "flow" position within the containing element?
Here I used a relative position of
-100px
to do that.I added a container with a background color so you can see the three elements are positioned within that block.
What you expected can be done with setting the position of the "middle" element as "relative" and changing the "top" property value like below:
And "position: sticky" is not applicable here.