How to animate calculated position/container height when viewport changes?

27 Views Asked by At

I have layout that has button sticked to bottom of the screen. Currently it's done with flexbox (content is flex 1 and button has fixed height).

The problem is with mobile browsers, I have used dvh for outer container, that way it sticks to bottom even with browser bar.

On Android chrome the bar hides on scrolling (even though there is no scroll on the page ), viewport changes dimensions, and button jumps to the bottom. I want to smooth this transition, and have no idea how to approach animating such movement.

(Tips on other ways to solve this problem also welcome)

1

There are 1 best solutions below

0
texi On

To make sure things move smoothly when you scroll or change the size of your screen, like when those bars pop up or disappear on your phone, you can use a mix of CSS transitions and JavaScript. This Code should solve the problem.

HTML:

<div id="container">
  <div id="content">Main Content</div>
  <button id="button">Button</button>
</div>

CSS:

html, body {
  margin: 0;
}

#container {
  position: relative;
  height: 100vh; /* Initial height */
  transition: height 0.5s ease; /* Smooth transition for height */
}

#content {
    text-align: center;
    font-size: 2rem;
}

#button {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 45px;
}

/* Add additional styling as needed */

JavaScript (necessary for mobile):

window.addEventListener('resize', function() {
  // Calculate new container height based on viewport size
  var newHeight = window.innerHeight;
  
  // Apply the new height to the container
  document.getElementById('container').style.height = newHeight + 'px';
});