Diolor
Diolor

Reputation: 13450

Change scrolling position when div height changes

Let's say we have a div A with a big height value and below other divs B, C....

If the user is seeing B or C and A reduces its height by e.g. half, then the scrolling position will remain the same, but the divs B,C will move by that amount to the top. So the next divs E,F,G ... will be displayed.

Is there any css value which can help keep, in this case, B or C in display rather than move them up? Or is it only possible by js (and scrolling negatively the height change amount)?

Upvotes: 2

Views: 4178

Answers (2)

zeddy
zeddy

Reputation: 31

Im not entirely sure what you mean by "reducing its height" but u cant change the height and move a div using strictly HTML and CSS. You can look up the before/after css.

Or you'll need a script. There are Javascript libraries that can make it easier such as Scroll Magic. It allows you to drop a script in your HTML page and use "controllers" to set the offset point.

http://scrollmagic.io/docs/index.html

Upvotes: 0

Amr Noman
Amr Noman

Reputation: 2637

You will have to adjust current scroll after resizing your element, try this and if it works for you adjust it for your needs.

This demo will resize the first element after 3 seconds and modify the scroll position accordingly.

const target = document.querySelector('.target');

function resizeTarget(newHeight) {
  const doc = document.documentElement;
  const top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
  target.style.height = newHeight + 'px';
  const viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  if (target.offsetTop + newHeight < top + viewportHeight ) {
	  window.scroll(0, top - newHeight);
  }
}

setTimeout(() => {
  resizeTarget(200);
}, 3000);
.box {
  width: 300px;
  height: 200px;
  background: tomato;
  margin: 10px;
}

.target {
  height: 400px;
  background: teal;
}
<div class="box target"></div>
<div class="box"></div>
<div class="box"></div>

Upvotes: 1

Related Questions