i try to center an element via position sticky. but i want to position it relative to its container element. the height of the container and the height of the sticky element are both variable. so in my example i have it at the position, where i want it to be, but it is not relative to its container.
but the element is clearly to far up top. it should only start within the container element, place itself at the center of the screen (top:50%, transform: translateY(-50%)) and stick as long as the container element goes. is that even possible?
.grid {
display: grid;
align-items: start;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
padding: 500px 0;
position: relative;
}
.column {
min-height: 800px;
background-color: red;
position: relative;
}
.sticky {
position: sticky;
top: 50%;
transform: translateY(-50%);
background-color: black;
}
<div class="grid">
<div class="column">
<div class="sticky" style="height: 500px;"></div>
</div>
<div class="column">
</div>
<div class="column">
<div class="sticky" style="height: 30px;"></div>
</div>
</div>
Given your additional comments I think I have a solution but it will require javascript. What you need to do so that the box respects it's parents boundries is to remove the translateY
and just use a calculation of 50% minus the boxes height/2 as a distance to the screen boundries which is essentially what the translate did. Btw you had a lot of redundant postion relatives.
document.addEventListener('DOMContentLoaded', function() {
const div = document.querySelector('#sticky');
if (div) {
const divHeight = div.offsetHeight;
document.documentElement.style.setProperty('--div-height', `${divHeight}px`);
}
});
.grid {
display: grid;
align-items: start;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
padding: 300px 0;
}
.column {
min-height: 500px;
background-color: red;
}
.center {
display: flex;
flex-flow: column nowrap;
justify-content: center;
}
#sticky {
position: sticky;
top: calc(50% - (var(--div-height) / 2));
bottom: calc(50% - (var(--div-height) / 2));
min-height: 100px;
background-color: black;
}
<div class="grid">
<div class="column center">
<div id="sticky"></div>
</div>
<div class="column"></div>
<div class="column"></div>
</div>