Home > Software design >  CSS Transition height when element appended to div
CSS Transition height when element appended to div

Time:10-29

Hello I want to transition div's height smoothly when I append an element to it, but I cannot get it to work I read this SO post smooth growing of div when appending children using transitions

but it does not answer the question correctly as it is fading in the element opposed to transitioning the div's height that the elements are in

http://jsfiddle.net/nexq40oz/

setInterval(function() {
    var li = document.createElement("li");
    li.innerHTML = "item";
    document.getElementById("list").appendChild(li);
}, 1000);
#menu #list {
    max-height: 300px;
    transition: max-height 0.15s ease-out;
    background: #d5d5d5;
}
<div id="menu">
    <ul id="list">
        <!-- Create a bunch, or not a bunch, of li's to see the timing. -->
        <li>item</li>
        <li>item</li>
    </ul>
</div>

CodePudding user response:

You need to add a class that transition the max-height of the li element and add with requestAnimationFrame to have an effect on the parent element,

setInterval(function() {
    var li = document.createElement("li");
    li.innerHTML = "item";
    document.getElementById("list").appendChild(li);
    requestAnimationFrame(() => requestAnimationFrame(() => li.classList.add('expand')))

}, 1000);
#menu #list {
    background: #d5d5d5;
}

#menu #list li {
  max-height: 0;
  transition: max-height 1s ease-out;
}

#menu #list li.expand {
  max-height: 200px;
}
<div id="menu">
    <ul id="list">
        <!-- Create a bunch, or not a bunch, of li's to see the timing. -->
        <li>item</li>
        <li>item</li>
    </ul>
</div>

CodePudding user response:

const ul = document.getElementById('list');
const item = document.querySelector('#list > li');

setInterval(function() {
  let h = ul.offsetHeight;
  let h_item = item.offsetHeight;

  var li = document.createElement("li");
  li.innerHTML = "item";
  document.getElementById("list").appendChild(li);

  ul.style.maxHeight = 'calc('   h   'px   '   h_item   'px)';
}, 1000);
#menu #list {
  overflow: hidden;
  max-height: 20px;
  transition: max-height 0.15s ease-out;
  background: #d5d5d5;
}

#list>li {
  height: 20px;
}
<div id="menu">
  <a>hover me</a>
  <ul id="list">
    <!-- Create a bunch, or not a bunch, of li's to see the timing. -->
    <li>item</li>
  </ul>
</div>

  • Related