* {
margin: 0;
padding: 0;
}
p {
text-align: justify;
}
.container {
margin: 15px auto;
border: 2px solid #FF0000;
background-color: #69D818;
width: 80%;
height: 6000px;
}
h1 {
background-color: #0013FF;
}
#first {
position: sticky;
top: 10px;
}
#second {
position: fixed;
top: 200px;
}
#third {
position: absolute;
width: 100%;
top: 250px;
}
#fourth {
position: relative;
top: 50px;
}
<div class="container">
<h1 id="first">Position Sticky</h1>
<h1 id="second">Position Fixed</h1>
<h1 id="third">Position Absolute</h1>
<h1 id="fourth">Position Relative</h1>
</div>
In the above code css position is not working. When I scroll down heading is not sticked to top position. But when I reach scroll upward sticky property is working. Another problem is that position: absolute heading is of width:100% and it goes out of the div container but I think it should be in the div container. Help
2
Answers
position: sticky
works, it’s just that the element overlaps, because you need to specify a higherz-index
.An element with an
position: absolute;
will occupy 100% of the width of the.container
if it is given aposition: relative;
:It does work, you just can’t see it because it overlaps.
A higher
z-index
number makes it go higher up in the Z dimension (closer to you in the screen). So, to prevent overlap, you need to specify az-index
:Full working example:
More information about the
z-index
property, you can go to: