Reputation: 852
I have an ul and inside the li, I have a child div. When I scroll inside the ul, I want the child div to remain positioned relative to the ul. I am able to get the desired result using position static on the ul and li, but when I change the position of the ul and li to relative, it doesn't work.
<ul class="grandparent">
<li class="parent">
<div class="child">
Child
</div>
<div >
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
</div>
</li>
<li>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
</div>
</li>
</ul>
Here is a link of the working copy https://jsfiddle.net/4jhzfm1s/1/
So my question is, how can I get the desired effect while having the ul and li as relative positioned.
Upvotes: 0
Views: 1325
Reputation: 105873
If you make the parent scroll and keep only grandparent in relative, it works as expected:
.grandparent {
position: relative;
}
.parent {
height: 100px;
overflow: auto;
}
.child {
position: absolute;
top: 50px;
left: 50%;
}
<ul class="grandparent">
<li class="parent">
<div class="child">
Child
</div>
<div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
</div>
</li>
</ul>
You can also set top:auto and margin-top:50px , so you can have multiple elements set in absolute(alike fixed) example https://jsfiddle.net/4jhzfm1s/3/
Upvotes: 1
Reputation: 5118
So you want the .child to remain where it is no matter where you scroll right? If that's the case I would wrap the ul
in a div and give that position: relative
as follows:
.wrapper {
position: relative;
}
.grandparent{
height:100px;
overflow:auto;
}
.child{
position:absolute;
top:50px;
left:50%;
}
<div class="wrapper">
<ul class="grandparent">
<li class="parent">
<div class="child">
Child
</div>
<div >
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
<div>
Spam
</div>
</div>
</li>
</ul>
</div>
Upvotes: 0