I want a gradient to stick to the top of my scrolling div.
If I try to use position absolute, it works when scrolled to the top, but when you scroll, the gradient scrolls away:
div {
background-color: red;
width: 200px;
height: 200px;
overflow-y: scroll;
position: relative;
}
p {
border: solid 1px blue;
height: 300px;
}
div::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 1em;
background: linear-gradient(to bottom, green, transparent);
}
<div>
<p>hello</p>
</div>
The fix seems to be to use sticky, which makes it stick to the top no matter the scroll position:
div {
background-color: red;
width: 200px;
height: 200px;
overflow-y: scroll;
position: relative;
}
p {
border: solid 1px blue;
height: 300px;
}
div::before {
content: '';
position: sticky;
top: 0;
left: 0;
width: 100%;
height: 1em;
background: linear-gradient(to bottom, green, transparent);
display: block;
}
<div>
<p>hello</p>
</div>
The problem with this method is when you are scrolled to the top, the gradient appears above the top element, instead of layered on top of it.
Is there any proper way to do this, or a way to fix it without adding more wrappers?
2
Answers
Instead of positioning the gradient background-image above the
div
with a pseudo-element, use it for thediv
itself.Maybe you want to remove the margin of the
p
as well?