Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS height animation on element with dynamic height [duplicate]

I have a div with dynamic height, and I want to use animation when the height grows. The problem is that I can't set the div's height (it has to be dynamic), so there's nothing to animate on.

.text {
  transition: all .3s ease-in-out;
  min-height: 20px;
  max-height: 200px;
  overflow: auto;
}

.max {
  transition: all .3s ease-in-out;
  height: 200px;
  min-height: 200px;
}

https://jsfiddle.net/abk7yu34/5/

Note that the shrinking animation works because the div has min-height.

Is there a way to solve this in pure CSS?

like image 746
Nir Smadar Avatar asked May 21 '17 14:05

Nir Smadar


2 Answers

Remove the height: 200px;, so you have both animate for expand and collapse.

Also, use the following to add animate on new line:

@keyframes lineInserted {
  from {
    height: 0;
  }
  to {
    height: 20px; /* your line height here */
  }
}
div[contenteditable] > div {
  animation-duration: 0.3s;
  animation-name: lineInserted;
  transition: height 0.3s;
}

document.querySelector('#button').addEventListener('click', function() {
  document.querySelector('.text').classList.toggle('max');
});
.text {
  background: green;
  color: #fff;
  transition: all .3s ease-in-out;
  min-height: 20px;
  max-height: 200px;
  overflow: auto;
}

.max {
  transition: all .3s ease-in-out;
  min-height: 200px;
}

@keyframes lineInserted {
  from {
    height: 0;
  }
  to {
    height: 20px; /* your line height here */
  }
}
div[contenteditable] > div {
  animation-duration: 0.3s;
  animation-name: lineInserted;
  transition: height 0.3s;
}
<div class="text" contentEditable="true"></div>
<button id="button">Click</button>
like image 137
Dalin Huang Avatar answered Oct 04 '22 14:10

Dalin Huang


Try removing the max-height attribute on the text class and transitioning to a new (dynamic) min height

.text {
    background: green;
    color: #fff;
    transition: min-height .3s ease-in-out;
    min-height: 20px;
    overflow: auto;
}

.max {
    transition: min-height .3s ease-in-out;
    min-height: 200px;
}

https://jsfiddle.net/Alessi42/abk7yu34/8/

Does this give the desired effect?

like image 40
Alessi 42 Avatar answered Oct 04 '22 14:10

Alessi 42