0

Is it possible to make a div transition from one auto height to another when the content of that div changes?

Ex: I have a div with height: auto; and that div contains ten rows of text. Can I transition the height of that div if I add/remove ex. 5 rows (and still have that height set to auto)?

hetasbo
  • 92
  • 8

1 Answers1

-1

It is... BUT!

In CSS, you can't transition a height: auto to another height: auto you HAVE to provide 2 values to transition between them. However, we can achieve - nearly - the same effect using padding!.

let textContainer = document.querySelector(".content")

// Hover to change the content
textContainer.addEventListener("mouseover", function() {
  textContainer.innerHTML = "Lorem Ipsum<br> is simply dummy text<br> of the printing and typesetting<br>"
  textContainer.classList.toggle("animated")
})

// Back to its normal
textContainer.addEventListener("mouseout", function() {
  textContainer.innerHTML = "Dummy Content</br>Another Line..."
  textContainer.classList.toggle("animated")
})
.content {
  width: 150px;
  background: #e9e9e9;
  transition: all 300ms ease;
  padding: 0 10px;
}
.animated {
  padding: 20px 10px;
}
<div class="content">
  Dummy Content<br>
  Another Line...
</div>

To get the best result, you can manipulate the following:

  • padding
  • transition-timing-function

This is probably the cleanest way to achieve what you need!

NOTE: There is no need to use height: auto as we don't rely on it.

Elharony
  • 886
  • 8
  • 18
  • I wonder why I got downvoted? So that I can improve my answers next time! – Elharony Oct 02 '18 at 14:39
  • Well, if that downvote because of using `JavaScript` code and the question need `CSS Only` solution... I used the JS to simulate the `mouseover` and `mouseout` effects and add some text to that box. But, the CSS only is all about adding that `.animated` class - for example; when hovering! – Elharony Oct 03 '18 at 07:03