I wanted to make a child fixed to the body at a certain position but not allow it to overflow its parent div.
body {
width: 100%;
height: 300vh;
margin: 0;
background: black;
color: white;
}
.parent{
width: 100%;
height: 100vh;
background: orange;
position: relative;
overflow:hidden;
}
.child {
position: fixed;
top: 45%;
left: 40%;
font-size: 3em;
background: rgba(0, 0, 0, .5);
padding: .4em .7em;
}
<div class='parent'>
<div class='child'>child</div>
</div>
here is the running codepen for this example – https://codepen.io/kartikth40/pen/xxmKRLV?editors=1100
If you scroll down the page in this example the child element will stick to the window but I wanted it to not overflow the parent(orange div).
3
Answers
Try using position:absolute and position:relative like this:
The easiest way is the usage of
position: sticky
in your case. You have to remove.parent {position: relative; overflow: hidden; }
:position: sticky
is a combination ofposition: static
andposition: fixed
.The element will remain static until the declared top/right/bottom/left position has been reached. At that point, it will be sticky (
position: fixed
) and remain at that position relative to the viewport. The main difference is, that the element is not completely removed out of flow. That means, the element remains a child element of the parent and will leave the viewport as soon as the parent levels the screen.What I also removed where
left: 40%
which you only used to center the element. However, that method does not work with position: sticky and is only a pure guess that is not very responsive. To center a block element you can give it a specific width (smaller then the parent element)and then center it withmargin: 0 auto
Here is another way with JS:
This JavaScript code tracks when a user scrolls the page.
It calculates the positions of the parent and child elements on the screen.
As the user scrolls, the child element’s position is adjusted to stay within its parent’s boundaries using the calculated values.
This way, the child element appears fixed to the screen but constrained within its parent’s dimensions.