Let’s say I have the following HTML and CSS and jQuery:
$("#blue_square").css("top", $(window).height() / 2 - 80)
.divTwo {
position: relative;
}
#blue_square {
position: fixed;
right: 0;
z-index: 9;
width: 370px;
box-shadow: 0 0 6px transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="divOne"></div>
<div class="divTwo">
<div class="col-md-12 col-sm-10">
<div id="blue_square" style="top: 310px;">Blue</div>
</div>
</div>
<div class="divThree"></div>
The problem I am noticing is that the blue_square
div element, is somehow showing up on divOne
but I was only expecting it to start from divTwo
.
My question is, how do I make blue_square
to start inside divtwo
and have it contained with in the divtwo
while I scroll its content?
I only want to see position blue_square position: fixed element inside divTwo
and that’s it. I don’t want to see it on divOne
or divThree
when I am scrolling their content. How can I achieve this with JavaScript?
2
Answers
Just change the css from fixed to absolute css and it will work according to your requirement:-
For this specific use case you could use
position:sticky
but if you want to position it based on theright
you will have to use some creative calculation withcalc
and apply it to theleft
(since the left/right/top/bottom are offsets from its initial position)A more robust solution would be to use
position:relative
on the#blue_square
andposition:relative
on its container, and then use another element for the scrolling content. So it would require some changes to the html/css structure(something like the following)