Estoy tratando de crear una barra lateral que contenga 2 elementos adhesivos. El problema es que cuando se cambia el tamaño de la pantalla, los elementos comienzan a superponerse entre sí. Quería encontrar una manera de evitar esa superposición y agregar un 'margen entre' mínimo.
body { height: 200vh; } .sidebar { display: flex; flex-direction: column; justify-content: space-between; height: 100vh; } .topSticky { position: sticky; top: 2rem; padding-bottom: 2rem; width: 100px; height: 100px; border: 1px solid black; } .bottomSticky { position: sticky; bottom: 2rem; width: 100px; height: 100px; border: 1px solid black; } <div class="sidebar"> <aside class="topSticky">Top sticky</aside> <aside class="bottomSticky">Bottom sticky</aside> </div>También probé varias formas de detectar colisiones, pero era demasiado complejo para observar y cubrir todos los casos.
Hay algunos problemas y limitaciones:
¿Cómo puedo lograr ese comportamiento? En esencia, debería encontrar una manera de evitar la superposición.
Gracias.
Hice un violín. ¿Es esto lo que estás tratando de lograr?
https://jsfiddle.net/g7y04dv5/
Solo modifiqué el JavaScript, pero hice algunos cambios de estilo a través de JavaScript para que sea visualmente más claro lo que está sucediendo...
// get the sticky elements and their container const first = document.querySelector('.topSticky'); const second = document.querySelector('.bottomSticky'); const sideBar = document.querySelector('.sidebar'); // make some temporary styling amends so we can see what is happening better sideBar.style.background = 'linear-gradient(20deg, pink, #6275ff)'; sideBar.style.height = '2000px'; sideBar.style.borderBottom = '300px solid beige'; document.querySelector('body').style.margin = 0; function stickyMe() { const aRem = 16; // roughly a rem const marginBetween = aRem * 2; // roughly 2 rem const containerHeight = window.innerHeight; // height of the window const firstHeight = first.offsetHeight; // height of first sticky element const secondHeight = second.offsetHeight; // height of second sticky element const minimimGap = firstHeight + secondHeight + marginBetween + (aRem * 4); // height of both sticky elements plus their gaps between eachother and the window if (containerHeight <= minimimGap) { // if the window height is less or equal to the minimimGap const newTopPosition = containerHeight - minimimGap; first.style.transform = 'translateY(' + newTopPosition + 'px)'; // pull the first sticky element up by the amount smaller the window is compared to the minimumGap } else { first.style.transform = 'none'; // if the gap is large enough for the 2 elements to not overlap then return to normal state } } window.addEventListener('DOMContentLoaded', stickyMe);; window.addEventListener('scroll', stickyMe); window.addEventListener('resize', stickyMe);