0

please tell me how to make the container smoothly increase in height and decrease depending on the height of the child element My code work without animation

setTimeout(() => {
  document.getElementById("page1").style = "display:none";
  document.getElementById("page2").style = "display:block";
}, 5000);

setTimeout(() => {
  document.getElementById("page1").style = "display:none";
  document.getElementById("page2").style = "display:block";
}, 15000);
.container {
  width: 50vmin;
  background: green;
  transition: all 5s ease;
  display: block;
}

#page1 {
  width: 25vmin;
  height: 50vmin;
  background: red;
  display: block;
}

#page2 {
  width: 25vmin;
  height: 10vmin;
  background: black;
  display: none;
}
<div class="container">
  <div id="page1"></div>
  <div id="page2"></div>
</div>
Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
alexanne
  • 131
  • 7

1 Answers1

1

Whenever you apply a transition, apply the transition animation to the element you want to watch and make it smooth animation.

Also note: Instead of updating display none and block, as you want to watch the height animation, update the style height style.

Here is a working example:

setTimeout(() => {
  document.getElementById("page1").style = "height:20vmin";
  document.getElementById("page2").style = "height:20vmin";
}, 5000);
.container {
  width: 50vmin;
  background: green;
  display: block;
}

#page1 {
  width: 25vmin;
  height: 50vmin;
  background: red;
  display: block;
  transition: all 5s ease;
}

#page2 {
  width: 25vmin;
  height: 10vmin;
  background: black;
  display: none;
  transition: all 5s ease;
}
<div class="container">
  <div id="page1"></div>
  <div id="page2"></div>
</div>
Riyaz Khan
  • 2,765
  • 2
  • 15
  • 29
  • Thanks, but is it possible that the size of the parent changes depending on the size of the child. I just don't know the height of the child component, it depends on the number of nested components... – alexanne Mar 29 '21 at 21:05
  • @alexanne, it's possible. You can get it by using targettedElement.offsetHeight or targettedElement.clientHeight – Riyaz Khan Mar 29 '21 at 21:09